Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy-constructor inheritance

struct A{
  virtual void what() { cout << "Base" << endl; };
};

struct B : A {
  virtual void what() { cout << "Sub" << endl; };
  int m;
  B() : m(10) {};
  B(const A & x) : m(50) {};
};

void main() {
  B b1;
  B b2 = b1;
  cout << "Number:  "
       << b2.m << endl;
};

Why isn't b2.m = 50? I'm trying to copy a b-object and i have the copy constructor B(const A & x) : m(50). Do i need need to make a copy c'tor for the derived class ass well ? Like B(const B&x) ?? I thought since a b-object has an a part, we could use B(const A & x) : m(50) instead of the default constructor: :S

In the case where you have a function with the parameter of an A object, you can send in a B object. How come it differs with the copy constructor?

like image 473
shizzle Avatar asked Oct 15 '11 15:10

shizzle


2 Answers

The reason is that B(const A& x) is not a copy-ctor — copy constructor for type T must always take an lvalue reference to T as the first (and have no other non-default arguments) argument. Your class has no defined copy-ctor, so the compiler generates the default one, which does a member-wise copy, hence why b2.m is the same as b1.m.

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

like image 92
Cat Plus Plus Avatar answered Oct 12 '22 22:10

Cat Plus Plus


Copy constructors need to be of the same type.

You haven't actually made a copy constructor. B(const A & x) is just a constructor that takes a const A by reference.

So, you don't need to make one for the derived class "as well", but "at all". As you stated, the type of this will be B(const B &x).

like image 28
Nate Avatar answered Oct 13 '22 00:10

Nate