Download this source file
// Slice2.cpp - Slicing copy example. In this version, the
// problem has been fixed by explicitly invokong operator= for
// the Base class sub-object. Note that just as with pointers,
// a reference to a Derrived object can be used where a reference
// to a Base object is required (provided public inheritance has
// been used).
#include
using namespace std;
class Base
{
public:
Base (const int v1=32, const int v2=64) { a1 = v1; a2 = v2;}
Base& operator= (const Base& other)
{ if (&other == this) return *this; // Check for self-assignment.
a1 = other.a1; a2 = other.a2;
return *this;
}
void display () const
{ cout << "Base class values: " << a1
<< ", " << a2 << endl;
}
private:
int a1, a2;
};
class Derrived: public Base
{
public:
Derrived (int v1=0, int v2=0, int v3=37, int v4=57) : Base(v1, v2)
{ b1 = v3; b2 = v4; }
Derrived& operator= (const Derrived& other)
{ if (&other == this) return *this; // Check for self-assignment.
Base::operator=(other);
b1 = other.b1; b2 = other.b2;
return *this;
}
void display () const
{ Base::display();
cout << "Derrived class values: " << b1
<< ", " << b2 << endl;
}
private:
int b1, b2;
};
int main ()
{
Derrived obj1;
Derrived obj2(1, 2, 3, 4);
obj1 = obj2;
obj1.display();
return 0;
}