user11001
user11001

Reputation: 372

Inheritance in c++, output inside

i have this code: the details comes after..

#include <iostream> 
using namespace std;
template <class T>
class A {
public:
    A() { cout << "A::A()" << endl; }
    A(const A& a) :i(a.i) { cout << "A::A(A&)" << endl; }
private:
    T i;
};
template <class T>
class B {
public:
    B(A<T> aa) : a(aa) { cout << "B::B(A)" << endl; }
    B(const B& b) : a(b.a) { cout << "B::B(B&)" << endl; }
    A<T> a;
};
class C : public B<int> {
public:
    C(A<int> aa) : B<int>(aa), a(aa){ cout << "C::C(A aa)" << endl; }
    ~C() { cout << "C::~C()" << endl; }
    A<int> a;
};
void main()
{
    cout << "--1--" << endl;
    A<int> a;
    cout << "--2--" << endl;
    C c(a);
}

and the output is:

--1--
A::A()
--2--
A::A(A&)
A::A(A&)
A::A(A&)
B::B(A)
A::A(A&)
C::C(A aa)
C::~C()
Press any key to continue . . .

my question is why copy constructor of class A called 3 times before constructor of class B ??

thanks guys.

Upvotes: 0

Views: 55

Answers (3)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

C(A aa) : B(aa), a(aa) calls

1.B<int>(aa) -- calls B(A<T> aa), call by value, so A::A(const A& a) is called
2. a(aa) -- calls A::A(const A& a)
3. C(A<int> aa) (aa passed by value, so, A::A(const A& a) is called

Thst's why you have copy constructor of class A called 3 times

Upvotes: 0

Neil Kirk
Neil Kirk

Reputation: 21773

First you pass to C(A<int> aa) which is a copy This goes to B(A<T> aa) which is a copy Then it's copied again here a(aa)

Pass by const reference to avoid these copies.

Just so you are aware, these classes do not need an explicitly defined copy constructor.

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254471

It's quite clear if you follow the chain of constructor calls:

  • Once to pass a copy of a by value to the constructor of C.
  • Once to pass a copy of that by value to the constructor of B.
  • Once to copy-construct the member a of B.

You can avoid the first two by changing those constructors to take their argument by reference, as the copy-constructor of A does.

Upvotes: 2

Related Questions