Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance initializer list

I am very new to C++, but I come from a Java background so I understand most of the OOP concepts. I am reading through an introductory guide and I came across this example:

[Foo.H] 
class A
{
    public:
       A(int something);
};

class B : public A
{
    public:
       B(int something);
};

[Foo.C] 
#include "Foo.H"

A::A(int something)
{
    printf("Something = %d\n", something);
}

B::B(int something) : A(something)
{
}

Is it correct to assume that by passing A(something) to the initializer list of B::B(int something) it is similar to the super keyword in java -- aka, it will execute A::A(int something)'s code? Also, why do I only call A(something) instead of A::A(something) from the initalizer list?

Basically I am asking: is the above equivalent to this:

B::B(int something)
{
    A::A(something)
}

Let me expand why I am confused.

If I were to use:

B::B(int something) : A(something)
{
    int x = 5;
    printf("x = %d", x);
}

And call the code via

B::B(7);

Would this print out x = 5 or something = 7 first? And why would it execute in this order?

I am just a little confused as to the syntax which is making it hard to grasp and visualize the inheritance happening in even this simple example.

like image 332
MrHappyAsthma Avatar asked Dec 17 '25 17:12

MrHappyAsthma


1 Answers

Yes, A(something) passes that value much like super. You don't have to use A::A because the language automatically injects the base class name into the child class.

It's not however equivalent to

B::B(int something)
{
    A::A(something)
}

because that's not legal code. You can only select which parent constructor to call in the initializer list.

As for your question about printing...did you try it? You'll see that the parent something= prints first followed by x=.

like image 110
Mark B Avatar answered Dec 19 '25 06:12

Mark B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!