I have a (probably very simple) problem with copy constructors in derived classes...
The problem is basically that I have a base class, and then a derived class, which both have copy constructors defined. Now, when I try to create an object of Derived using the copy constructor, only the base class copy constructor is being called!
However, this poses another question for me (which is the situation I have in the classes i'm writing):
If I have three classes; A (base class), B(derived class of A) and C (derived class of A).. basically:
A
/ \
B C
and a copy between a B object and a C object is allowed,
1 2
B b;
C c(b);
Would it still work when I have "Derived&" in the copy constructor? This is the initial reason why I had Base& in the copy constructor of Derived..
Thanks again for the response.
and a copy between a B object and a C object is allowed,
This is quite abnormal.
But if you want that to work you'd have to write another ctor:
1 2 3 4 5 6 7 8
// either have this ctor...
C::C(const B&);
// or if you only want to copy the A elements you can have this instead...
C::C(const A&); // you can do this instead
// either way, you can still have the normal copy ctor:
C::C(const C&);
Ok I ran into new problems when defining the copy constructor with Julian& instead of Date&:
1 2 3 4
Julian j1;
Date & d1 = j1;
Julian j2(d1); // compiler complains on this line.
The above code doesn't compile (but it is supposed to) when the copy constructor in Julian is declared as
1 2 3
Julian(const Julian& ref): Date(ref) {
...
}
The error I receive is:
error C2664: 'lab2::Julian::Julian(const lab2::Julian &)' : cannot convert parameter 1 from 'lab2::Date' to 'const lab2::Julian &'
1> Reason: cannot convert from 'lab2::Date' to 'const lab2::Julian'
It compiles fine when the param in the copy constructor is const Date& ref... but then the actual body of the Julian copy ctor isn't executed at all as I explained earlier....
And the compiler will choose which one to use. I'm guessing the reason it wasn't executing at first was because the compiler didn't find a suitable copy ctor in Julian, and therefore just used the default copy ctor..?