This example was taken from Bruce Eckel's "Thinking in C++" Chapter 14, Section "Upcasting and the Copy Constructor".
#include <iostream>
using namespace std;
class Parent
{
int i;
public:
Parent(int ii) : i(ii) { cout << "Parent(int ii)\n"; }
Parent(const Parent& b) : i(b.i) { cout << "Parent(const Parent&)\n"; }
Parent() : i(0) { cout << "Parent()\n"; }
friend ostream& operator<<(ostream& os, const Parent& b)
{ return os << "Parent: " << b.i << endl; }
};
class Member
{
int i;
public:
Member(int ii) : i(ii) { cout << "Member(int ii)\n"; }
Member(const Member& m) : i(m.i) { cout << "Member(const Member&)\n"; }
friend ostream& operator<<(ostream& os, const Member& m)
{ return os << "Member: " << m.i << endl; }
};
class Child : public Parent
{
int i;
Member m;
public:
Child(int ii) : Parent(ii), i(ii), m(ii) { cout << "Child(int ii)\n"; }
friend ostream& operator<<(ostream& os, const Child& c)
{ return os << (Parent&)c << c.m << "Child: " << c.i << endl; }
};
int main() {
Child c(2);
cout << "calling copy-constructor: " << endl;
Child c2 = c;
cout << "values in c2:\n" << c2;
}
The author makes the following comment regarding this code :
"The operator<< for Child is interesting because of the way that it calls the operator<< for the Parent part within it : by casting the Child object to a Parent& (if you cast to a base-class object instead of a reference you will usually get undesirable results):
return os << (Parent&)c << c.m << "Child: " << c.i << endl;
I also run the program, by replacing the above instruction by :
return os << (Parent)c << c.m << "Child: " << c.i << endl;
and the propram runs without a problem, with just one expected difference. Now the Parent
copy constructor is called again to copy the argument c
to the Parent::operator<<()
.
What are then, the undesirable results the author is talking about ?