Answer to Question #188298 in C++ for zaid

Question #188298

Q1: Write a Program in C++ which completes following requirements:

a. Create a class, having a static function printing some information and invoke that method using scope resolution operator.

b. Try to access non-static data members from static method and write in comments what happens.

c. Declare and initialize a static variable as counter in a function (increment it in every call) and call it multiple times printing the change in value

d. Write about your observations while making this assignment in a word file about static variables and static methods.


1
Expert's answer
2021-05-02T17:47:59-0400
#include <iostream>


using namespace std;


class MyClass{
private:
    int x;
    static int counter;
    public:
        static void printInfo()
        {
            cout<<"Hello"<<endl;
            /*cout<<x;  This produces an error:
            invalid use of member MyClass::x in static function
            */
        }
        void getCouter()
        {
          counter++;
          cout<<"\nThis function has been called "<<counter<<" times.";
        }
};
int MyClass::counter = 0;


int main()
{
    MyClass::printInfo();
    MyClass mc;
    mc.getCouter();
    mc.getCouter();
    mc.getCouter();
    mc.getCouter();
    mc.getCouter();
    mc.getCouter();
    return 0;
}

Observations

  • A static variable can be used in a non-static function.
  • A static variable can only be initialized outside the class.
  • A static variable cannot access or use a non-static variable.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS