0

In C++ the memory is created only when we declare the object(s) for the respective class(s).
So when we make any member function as static inside the class, we are able to access that member function directly by the class name, without creating any object of the class. Then how the memory is allocated in this condition without any object.

Example program:

#include<iostream>
using namespace std;

class sample
{
    static int a,b;
    public:
    static void read()
    {
        cout<<"Enter integers:- ";
        cin>>a>>b;

        cout<<"a= "<<a<<endl;
        cout<<"b= "<<b<<endl;
    }
};

int sample::a;
int sample::b;

int main()
{
    sample::read(); //Accessing read() with the class name
    return 0;
}
  • That's exactly what `static` is for. It doesn't need an instance of the class. The initialization appears here: `int sample::a; int sample::b;` – πάντα ῥεῖ Sep 20 '20 at 15:30
  • https://stackoverflow.com/questions/3270427/when-is-memory-allotted-to-static-variables-in-c should help. Static variables are allocated in implementation-defined manner upon program startup, and they live until the program ends. They cannot be "freed" or "reallocated". – Omid CompSCI Sep 20 '20 at 15:31
  • @ Omid CompSCI Please help I din't understood from the above suggestions. Because my question was something else. – Molybdenum Oxide Sep 21 '20 at 11:16

0 Answers0