Objects Memory Allocation in C++
Despite coming from the same class, variables and functions are given memory in two separate ways. Only when the object is formed do the class variables receive memory allocation.
When the class is declared, the variables are not given any memory. Each object contains a unique copy of each variable in the class because single variables can simultaneously have varying values for various objects. However, when the class is declared, memory is only allotted to the function once. As a result, each object shares a single copy of the functions rather than having individual copies.
Static Data Members in C++
When a static data member is produced, just one copy of the data member is created and shared by all class objects. In most cases, unless the attributes are defined statically, each object has a unique copy of each attribute.
No object of the class defines the static members. They are only defined when the scope resolution operator is used outside of any function.
An illustration of the definition of static variables is
class Employee
{
public:
static int count; //returns number of employees
string eName;
void setName(string name)
{
eName = name;
count++;
}
};
int Employee::count = 0; //defining the value of count
Static Methods in C++
Static methods are independent of any object or class once they are generated. Only static data members and static methods can be accessed by static methods. The only way to access static methods is by utilising the scope resolution operator. The application of static methods in a programme is demonstrated.
#include <iostream>
using namespace std;
class Employee
{
public:
static int count; //static variable
string eName;
void setName(string name)
{
eName = name;
count++;
}
static int getCount()//static method
{
return count;
}
};
int Employee::count = 0; //defining the value of count
int main()
{
Employee Harry;
Harry.setName("Harry");
cout << Employee::getCount() << endl;
}
Output:
1