Class is not allocated any memory. This is partially true. The functions in a class are allocated memory which are shared by all the objects of a class. Only the data in a class is allocated memory when an object is created. Every object has its own memory for data (variables). For example consider the following Student class and its functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Student { private: string name; string regdno; string branch; int age; public: void get_details(); void show_details(); }; void Student::get_details() { cout << "Enter student name:"; cin >> name; cout << "Enter student regdno:"; cin >> regdno; cout << "Enter student branch:"; cin >> branch; cout << "Enter student age:"; cin >> age; } void Student::show_details() { cout << "—–Student Details—–" << endl; cout << "Student name: " << name << endl; cout << "Student regdno: " << regdno << endl; cout << "Student branch: " << branch << endl; cout << "Student age: " << age << endl; } |
Now let’s create two objects for the above Student class as follows:
Student std1, std2;
C++ allows us to declare variables or functions as static members by using the keyword static.
Static Data
Syntax for declaring a static variable is as follows:
static data-type variable-name;
Static data members will have the following properties:
- Only one copy of static data element will be created irrespective of the no. of objects created.
- All objects share the same copy of the static data element.
- All static data members are initialized to 0 when the first object for a class is created.
- Static data members are only visible within the class. But their lifetime is throughout the program.
Take your time to comment on this article.