< Previous | Contents | Next >
Using Overloaded Assignment Operators and Copy Constructors in Derived Classes
You already know how to write an overloaded assignment operator and a copy constructor for a class. However, writing them for a derived class requires a little bit more work because they aren’t inherited from a base class.
When you overload the assignment operator in a derived class, you usually want to call the assignment operator member function from the base class, which you can explicitly call using the base class name as a prefix. If Boss is derived from Enemy, the overloaded assignment operator member function defined in Boss could start:
Boss& operator=(const Boss& b)
{
Enemy::operator=(b); //handles the data members inherited from Enemy
//now take care of data members defined in Boss
The explicit call to Enemy’s assignment operator member function handles the data members inherited from Enemy. The rest of the member function would take care of the data members defined in Boss.
Introducing Polymorphism 347
For the copy constructor, you also usually want to call the copy constructor from a base class, which you can call just like any base class constructor. If Boss is derived from Enemy, the copy constructor defined in Boss could start:
Boss (const Boss& b): Enemy(b) //handles the data members inherited from Enemy
{
//now take care of data members defined in Boss
By calling Enemy’s copy constructor with Enemy(b), you copy that Enemy’s data members into the new Boss object. In the remainder of Boss’ copy constructor, you can take care of copying the data members declared in Boss into the new object.