Copy Constructors and Inheritance

Dec 2, 2009 at 3:15am
closed account (1yR4jE8b)
Just a question about how copy constructors work.

I have a base class A, with an implemented copy constructor.
I also have a derived class B, which does not add any new variables.

When I implement the copy constructor of B, does the copy constructor of A
get called implicitly or do I have to specify the call to the copy constructor of the base class somehow?
Dec 2, 2009 at 3:52am
If B does not have a copy constructor, the default copy constructor is used (which calls A's copy constructor)

If B has a copy constructor, its parents' copy constructors are called by default unless you explicitly call a different constructor.

Either way... A's copy ctor gets called. The only way to prevent A's copy ctor from being called is to explicitly call a different ctor.
Dec 2, 2009 at 12:59pm
Mmm, no.....

Unless B explicitly calls A's copy constructor, A's default constructor will be called instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

struct B {
  B() { std::cout << "B default ctor called" << std::endl; }
  B( const B& ) {
      std::cout << "B copy ctor called" << std::endl;
  }
};

struct A : B {
  A() { std::cout << "A default ctor called" << std::endl; }
  A( const A& ) {
      std::cout << "A copy ctor called" << std::endl;
  }
};

void Foo( A ) {
    std::cout << "Hello world" << std::endl;
}

int main() {
    A a1;
    Foo( a1 );
}


You will note that when copy construction is used to make a copy of A onto the stack for
the call to Foo(), A's copy constructor is called, but B's default constructor is called.

(sorry, I realized I reversed my A and B from the original meanings in the original post)
Dec 2, 2009 at 7:03pm
oh crap -- sorry about that!

Good save jsmith.
Topic archived. No new replies allowed.