Class contains static variable, then every object of the class has its copy of static variable - C++

Q.  If a class contains static variable, then every object of the class has its copy of static variable.
- Published on 17 Jul 15

a. True
b. False

ANSWER: False
 

    Discussion

  • Nihal   -Posted on 08 Oct 15
    If you declare static variable in a class then a single copy will be created for each object. Static variable have a scope till the program lifetime. You can declare class, method, variable as static.
    Example:
    class Demo
    {
    public:

    void counter()
    {
    static int count=0;
    cout << count++;
    }
    };
    void main()
    {
    Demo obj1;
    for(int i=0;i<5;i++)
    {
    obj1.counter();
    }
    }

    Output : 0 1 2 3 4
    If you run the same program's output without using static variable the output will be.
    0 0 0 0 0

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)