member variable

144 views Asked by At

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

There are 3 answers

0
Some programmer dude On BEST ANSWER

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.

2
justin On

in that case, you would use the initialization list of test's constructor to define the initial values for an instance like so:

class test {
    int i;
    int j;
  //...
public:
  test() : i(-12), j(4) {}
};
2
Wyzard On

That definition reserves space for one integer, but there'll really be a separate integer for every instance of the class that you create. There could be a million of them, if your program creates that many instances of test.

Space for a non-static member is allocated at runtime each time an instance of the class is created. It's initialized by the class's constructor. For example, if you wanted the integer test::i to be initialized to the number 42 in each instance, you'd write the constructor like this:

test::test(): i(42) {
}

Then if you do

test foo;
test bar;

you get two objects, each of which contains an integer with the value 42. (The values can change after that, of course.)