Initialize value of static variable of class only when object is created - C++ basic concepts

Q.  We can initialize a value of static variable of a class only when its object is created. No other initialization is permitted.
- Published on 17 Jul 15

a. True
b. False

ANSWER: False
 

    Discussion

  • Ramesh   -Posted on 24 Oct 15
    We have to initialize static variable outside the class.
    Example:
    class MyClass
    {
    static int var;
    public:
    void show()
    {
    cout<<"var=:"<< var;
    }
    };

    int MyClass :: var=10;
    void main()
    {
    MyClass obj;
    obj.show();
    }
  • Ramesh   -Posted on 24 Oct 15
    We have to initialize static variable outside the class.

    class MyClass
    {
    static int var;
    public:
    void show()
    {
    cout << "var=:" << var;
    }
    };

    int MyClass::var=10;
    void main()
    {
    MyClass obj;
    obj.show();
    }

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.)