Access specifiers in C++ are used to control the visibility of class members. There are three types of access specifiers in C++: public, private, and protected.
- Public members are accessible from anywhere outside the class.
- Private members are only accessible from within the class itself.
- Protected members are accessible from within the class itself and its derived classes.
Static data members are those members of a class that belong to the class itself rather than to any particular object of the class. A static data member is shared by all objects of the class, and there is only one copy of the member in the program. It is declared using the keyword 'static' and must be initialized outside the class.
Static member functions are functions that can be called on the class itself, rather than on an instance of the class. Like static data members, static member functions belong to the class itself rather than to any particular object of the class. They are also declared using the keyword 'static'.
Here's an example program that demonstrate the use of static data members and static member functions:
#include <iostream>
using namespace std;
class MyClass {
private:
static int count; // static data member
public:
static void printCount() { // static member function
cout << "Object count: " << count << endl;
}
MyClass() {
count++; // increment count each time an object is created
}
};
int MyClass::count = 0; // initialize static data member
int main() {
MyClass obj1, obj2, obj3; // create three objects
MyClass::printCount(); // call static member function on the class itself
return 0;
}
In this program, we have a class called 'MyClass' that has a static data member called 'count', which keeps track of the number of objects created from the class. We also have a static member function called 'printCount', which simply prints the value of 'count' to the console.
In the 'main' function, we create three objects of the 'MyClass' class and then call the 'printCount' function on the class itself using the scope resolution operator '::'. This allows us to call the function without needing to create an object of the class first.
No comments:
Post a Comment
If you have any doubts, please let me know