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
a)
#include <iostream>
using namespace std;
class Class{
public:
Class(){}
static void staticMethod(){
cout<<"Some information";
}
};
int main(){
Class::staticMethod();
return 0;
}
b)
#include <iostream>
using namespace std;
class Class{
int x;
public:
Class(){}
static void staticMethod(){
cout<<x; //compilation error. A nonstatic member reference must be relative to a specific object
}
};
c)
#include <iostream>
using namespace std;
int funcn(){
static int x = 0;
return ++x;
}
int main(){
cout<<funcn()<<endl;
cout<<funcn()<<endl;
cout<<funcn()<<endl;
return 0;
}
d)static class methods cannot use non-static data members
static variables retain their previous value in every function call.
Comments
Leave a comment