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.
#include <iostream>
using namespace std;
class ClassA{
private:
//define non-static data member
int a;
public:
//define a static member function
static void display()
{
cout<<"Some Information"<<endl;
//Try to access non-static data members from static method
/*cout<<a; This produces an error:
invalid use of member MyClass::a in static function
*/
}
void myfunction()
{
static int counter=1;
cout<<"\nCalling this function for the "<<counter<<" times";
counter++;
}
};
int main()
{
ClassA::display();
ClassA c;
c.myfunction();
c.myfunction();
c.myfunction();
c.myfunction();
return 0;
}
Observations
Comments
Leave a comment