Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Jul 31, 1998

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; 
	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;
	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
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date