Please Explain Me This Output

I have this code in Visual Studio 2008

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class base
{
protected:
	int i;

public:
	base()
	{
		cout << "In base" << &i << endl;
	}
};

class derived : public base
{
public:
	derived():base()
	{
		cout << "In Derived" << &i << endl;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
derived d1;
base b1;
getch();
return 0;
}


The output is

In base0012FF60
In Derived0012FF60
In base0012FF54


I understand this - when I create a derived class object, the Base class CTOR is first called and then the Derived class CTOR is called. However what is do not understand is, the value of variable i.

Why is it 0012FF60 twice and 0012FF54 when I create an object for the base class?

Also what does derived():base() in the derived class mean? I have seen codes like base::function_name() in the derived class but this derived():base() is something new to me.
Last edited on
Line 24 calls the base and derived class CTOR upon creating the derived class object.
Line 25 creates only the base class CTOR upon creating the base class object.

Both objects d1 and b1 have their own member variable i, hence the different addresses.

derived():base() means you explicitly want to call the base() constructor here. You can call any other constructor here which you define for the base class.
Call to the base class CTOR is added by the compiler.

base::function_name() is the way to specify the call to be for the member function_name() of base class.
mgupta Thanks for the reply.

derived():base() means you explicitly want to call the base() constructor here. You can call any other constructor here which you define for the base class.


But why would someone want to do that? Why can't we just use the derived class's CTOR alone?
closed account (1yR4jE8b)
The way it's written is kindof confusing, what that is is an intializer list. It is used before the body of the constructor to properly initialize the member variables.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
class Foo
{
public:
     Foo(int initX, int initY, int initZ);
private:
     int x, y, z;
};


Foo::Foo(int initX, int initY, int initZ)
: x(initX), y(initY), z(initZ) //initializes x, y, and z
{}


This is much preferred over doing it in the body of the constructor. When you are dealing with inheritance, the compiler will automatically call the default constructor of all base classes unless you specify it yourself:

1
2
3
4
5
6
7
8
9
10
11
12
class Bar : public Foo //using the Foo class from the previous code example
{
public:
     Bar(int initI);
private:
     int i;
};

Bar::Bar(int initI)
:  Foo::Foo(1, 3, 5), i(initI) //I don't think you need to use Foo::Foo, but I like to to be more verbose and readable
{}

Last edited on
Topic archived. No new replies allowed.