devxlogo

Calling the Operator =

Question:
How can I call the operator= of the base class from the operator=in the derived class?

The data member in the base class is a private data member. I want to be able to use operator = in the derived class and call the operator = in the base class

Answer:
I am assuming that the copy assignment operator in the base class iseither public or protected so that you can use it from the derived class.Given that assumption, here is a code snippet that does the exact same thing.

class Base{protected:	const Base &operator = (const Base &rhs)	{		data = rhs.data;		return *this;	}private:	int data;};class Derived  : public Base{public:	const Derived &operator =(const Derived &rhs)	{		// call base classes assignment first 		Base::operator=(rhs);		data = rhs.data;		return *this;	}private:	int data;};

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.