Simulating Inheritance of Assignment Operator

As opposed to base class’ constructor and destructor, which are automatically invoked from the derived class’ constructor and destructor respectively, a user-defined assignment operator defined in a base class is overridden – rather than being extended – when re-defined in a derived class. In order to extend the assignment operator in a derived class, one has first to invoke the base’s assignment operator explicitly, and then add the assignment operations required for the derived class.

 class C {char *p; public: 	enum {size = 10}; //size serves as a constant	const char * Getp() const {return p;}	C() : p ( new char [size] ) {}C& operator = (const C& other) {if (this != &other) 		strcpy(p, other.Getp() ); 		return *this;} //...destructor and copy constructor};class D : public C {	char *q;public: 	const char * Getq() const {return q;}	D(): q  ( new char [size] ) {}D& operator = (const D& other) { 		if (this != &other)  		C::operator=(other);  //first invoke base's assignment operator explicitly		strcpy(q, (other.Getq()));  //add extensions here		return *this;} //...destructor and copy constructor};
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: