I have these classes:
first:
class C
{
public:
C(const C& c):_s(c._s){}
c():_s(""){}
string _s;
}
second:
class C2: public C
{
public:
C2(const C2 & c2):_i(c2.i){}
C2():_i(0){}
int _i;
}
main:
int main()
{
C2 c2;
C2._s="hello";
c2._i=42;
C2 c3(c2);
cout<<c3._s<<" "<<c3._i<<endl;
}
and the output is 42. My question is, why is the output 42? A base constructor is always called before the derived constructors, so this line:
C2 c3(c2);
should call C‘s copy constructor and should copy “hello”, meaning the output should be hello. What am I missing out here?
The reason is
doesn’t initialize
_sto the values stored inc2because the default (parameterless) constructor of base class is called unless specified otherwise and so_sis also initialized with its default constructor, not copy constructor.Specifically in your case
C2::(const C2&)invokesC::C()and that invokesstring::string().You have to explicitly call the right base constructor: