#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() { i=1; j=2;};
A (A &obj) { i= obj.i+100; j= obj.j+100;};
int i;
int j;
};
class B:public A
{
public:
B():A() {i=10; j=20; k=30;};
B(A &obj) { A::A(obj); k=10000; };//
int k;
};
int main()
{
A dog;
B mouse(dog);
cout<<mouse.i<<endl;
cout<<mouse.k<<endl;
return 0;
}
I try to write a copy constructor for the derived class that takes advantage of the copy constructor for the base class. I expect that mouse.i should be 101, but in fact the compiling result is 1. The value for mouse.k is 10000, which is expected. I was wondering what’s wrong with my code.
In this constructor:
A::A(obj);does not initialise the base sub-object; instead, it creates a local object also calledobj. It’s equivalent toA::A obj;, which is equivalant toA obj;. [UPDATE: or possibly it does something else, or possibly it’s ill-formed – in any event, it’s wrong.]You want to use an initialiser list:
Also, you almost certainly want the constructor parameters to be
A const &, to allow construction from constant objects or temporaries.