Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ inheritance and constructors

class A {
public:
      A(int i): data(i) {cout << "A::A(" << i << ")" << endl;}
      A(const char* s): data(0) { cout << "A::A(" << s << ")"<< endl;}
      ~A() { cout << "A::~A()" << endl;}
private:
int data;
};

class B:public A {
public:
    B(const A& a): A(a){ std::cout << "B::B(const A& a)" << std::endl;}
     ~B() { std::cout << "B::~B()" << std::endl;}
};

int main() {
    B b0(0);
    B b1("abc");
return 0;
}

Pretty straightforward, can someone explain why the output is :

 A::A(0)
 B::B(const A& a)
 A::~A()
 A::A(abc)
 B::B(const A& a)
 A::~A()
 B::~B()
 A::~A()
 B::~B()
 A::~A()
like image 376
Jeremy Knees Avatar asked Nov 28 '25 19:11

Jeremy Knees


1 Answers

B b0(0); - there's no such constructor for B, so the compiler is looking for some constructor, that can be called with just one cast (one implicit cast is allowed, 2 are not), so it finds B::B(const A& a), because A has a constructor with only one parameter, and this is A::A(int i). This means, that 0 can be casted to int, so temporary A object is created (and destroyed, after B is created). So, here's why we have


 A::A(0)
 B::B(const A& a)
 A::~A()

Then the next is called: B b1("abc");, so here comes:


 A::A(abc)
 B::B(const A& a)
 A::~A()

This is absolutely the same as with int, but here with char*.

Then, both objects are destructed, so their destructors are called in the opposite order, as their constructors are called, that's where


 B::~B()
 A::~A()
 B::~B()
 A::~A()

comes from.

It looks confising, because you haven't overloaded A::A( const A& a) and you don't see, that it is called 2 times, too.

Cheers (:


A small edit: not A::A(), but A::A( const A& a) - thanks to Nim.

like image 134
Kiril Kirov Avatar answered Nov 30 '25 10:11

Kiril Kirov



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!