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.
// According to the results of the study, it can be seen that static functions can only work with static members.
#include <iostream>
using namespace std;
class Class
{
public:
Class();
static void Print();
private:
int nonStatic;
static int count;
};
int Class::count = 0;
Class::Class()
{
nonStatic = 15;
count++;
Print();
}
void Class::Print()
{
// cout << "Non static member: " << nonStatic << endl; // ERROR: Non statiс member
cout << "Static member: " << count << endl;
}
int main()
{
for (int i = 0; i < 10; i++)
{
Class* ptr = new Class;
}
system("pause");
return 0;
}
Comments
Leave a comment