0

I have a question about this code:

class A
{
public:
    A(){cout<<"A no parameter ";}
    A(string s){cout<<"A string parameter";}
    A(A &a){cout<<"A object A parameter";}
    
};

class B:public A
{
public:
    B(){cout<<"B no parameters";}
    B(string s){cout<< "B strig parameter";}
    B(int s){cout<<"B int parameter";}
    
};


int main() {
 

    A a2("Test");
    B b1(10);
    B b2(b1);

    
    return 0;
}

When I run this code, I get this result:

A string parameterA no parameter B int parameterA object A parameterProgram ended with exit code: 0"

I am actually not sure why the statement A no parameter shows up, even though I did not assign the statement about it.

I am studying coding for now, so I am glad if you explain this.

1
  • During construction of an object of a derived class, its base class subobject has to be constructed first, hence the call to A's constructor. Jan 7, 2021 at 22:53

1 Answer 1

4

Your issue is that in

B(string s) /*...*/ {cout<< "B strig parameter";}
//and
B(int s) /*...*/  {cout<<"B int parameter";}

that in the /*...*/ part you have an empty member initialization list. That means the compiler will insert one for you for the base class. Because of that the constructors actually become

B(string s) : A() {cout<< "B strig parameter";}
//and
B(int s) : A() {cout<<"B int parameter";}

and the A() part is what is calling A's default constructor.

2
  • I see that. So the A() part always comes with every constructor in B class even though I did not write :A() in every part, did it?
    – Sho
    Jan 7, 2021 at 22:49
  • @Sho Yes. All class members, and that includes base classes, must be initialized in the member initialization list. If you don't, the compiler will insert a default initializer for you. Jan 7, 2021 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.