Passing derived classes uninitialized variable to base class constructor !!

P

PSN

Hi all ..
can any one please explain the output of the following code ..

class A {
public:
int a1;
int a2;
A(int a1, int a2)
{
cout << "i am in AAA" << endl;
this->a1 = a1;
this->a2 = a2;
}
};

class B : public A {
public:
int b1;
int b2;
B(int b1, int b2, int a1, int a2) : A(b1, a2)
{
cout << "i am in BBB" << endl;
this->b1 = b1;
this->b2 = b2;
}
};

int main()
{
B test(10, 20, 30, 40);
cout << test.b1 << " " << test.b2 << " " << test.a1 << " " << test.a2
<< endl;
}


The result is:
I am in AAA
I am in BBB
10, 20, 10, 40

The constructor of A is called first .. therefore when i pass an
uninitialized value, "b1", to the constructor of the base, i was
expecting a crash or some junk value .. but i see that a1 is
initialized to 10. But when i comment out the initialization statement
of b1 (this->b1 = b1), i see a junk value for the variable a1 ... Can
someone please explain me this ..

thanks ...
 
B

Bo Persson

PSN said:
Hi all ..
can any one please explain the output of the following code ..

class A {
public:
int a1;
int a2;
A(int a1, int a2)
{
cout << "i am in AAA" << endl;
this->a1 = a1;
this->a2 = a2;
}
};

class B : public A {
public:
int b1;
int b2;
B(int b1, int b2, int a1, int a2) : A(b1, a2)
{
cout << "i am in BBB" << endl;
this->b1 = b1;
this->b2 = b2;
}
};

int main()
{
B test(10, 20, 30, 40);
cout << test.b1 << " " << test.b2 << " " << test.a1 << " " <<
test.a2
<< endl;
}


The result is:
I am in AAA
I am in BBB
10, 20, 10, 40

The constructor of A is called first .. therefore when i pass an
uninitialized value, "b1", to the constructor of the base, i was
expecting a crash or some junk value .. but i see that a1 is
initialized to 10.

You are not passing the member variable b1, but the constructor
parameter b1 to A's constructor.
But when i comment out the initialization statement
of b1 (this->b1 = b1), i see a junk value for the variable a1 ...
Can
someone please explain me this ..

I see a junk value for b1 (which is printed first!), not for a1.
That's as expected.


Bo Persson
 
P

PSN

I am sorry ...
i understand it now ..

the similar names made it confusing ..

thanks a lot ..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top