Reputation: 183
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?
Upvotes: 5
Views: 4211
Reputation: 129764
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 typeX&
,const X&
,volatile X&
orconst volatile X&
, and either there are no other parameters or else all other parameters have default arguments (8.3.6).
Upvotes: 14
Reputation: 7164
The default copy-ctor for classes of type B would be B(const B&). Since you haven't specified this one, the compiler kindly generates it for you.
Its different with user defined methods as those cannot be compiler generated.
Upvotes: 1
Reputation: 12819
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)
.
Upvotes: 1