Search code examples
c++constructorinitializationinitialization-list

member variable


Can there be a member variable in a class which is not static but which needs to be defined (as a static variable is defined for reserving memory)? If so, could I have an example? If not, then why are static members the only definable members?

BJARNE said if you want to use a member as an object ,you must define it.

But my program is showing error when i explicitly define a member variable:

class test{
    int i;
    int j;
  //...
};

int test::i; // error: i is not static member.

Solution

  • In your example, declaring i and j in the class also defines them.

    See this example:

    #include <iostream>
    
    class Foo
    {
    public:
        int a;         // Declares and defines a member variable
        static int b;  // Declare (only) a static member variable
    };
    
    int Foo::b;    // Define the static member variable
    

    You can now access a by declaring an object of type Foo, like this:

    Foo my_foo;
    my_foo.a = 10;
    std::cout << "a = " << my_foo.a << '\n';
    

    It's a little different for b: Because it is static it the same for all instance of Foo:

    Foo my_first_foo;
    Foo my_second_foo;
    
    Foo::b = 10;
    std::cout << "First b = " << my_first_foo.b << '\n';
    std::cout << "Second b = " << my_second_foo.b << '\n';
    std::cout << "Foo::b = " << Foo::b << '\n';
    

    For the above all will print that b is 10.