OpenSource For You

An alternate solution

-

Here one needs to declare assignment operator as virtual in the base class. This way the invocation will know which exact operator (base or derived) to call at runtime. You also need to define the overridden assignment operator in the derived class to accept the base class object as the parameter. After all, that’s what you intend to do (in the troublesom­e assignment mentioned above). We then need to define a copy() method, which will copy the members appropriat­ely. The derived class’s assignment operator needs to downcast the given base object and call these copy() methods appropriat­ely.

Remember, this approach has to be implemente­d for all derived classes. You can also choose to define the copy() method as protected if you want to avoid direct invocation of it.

The following complete example shows how this works.

Newspapers in English

Newspapers from India