Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment operator not available in derived class

The assignment operator in base class does not seem to be available in derived class. Given this code:

#include <iostream>  class A{     int value; public:     A& operator=(int value){         this->value = value;         return *this;     } };  class B : public A{};  int main(){     B b;     b = 0; // Does not work     return 0; } 

GCC 6.4 says:

error: no match for 'operator=' (operand types are 'B' and 'int')

What is happening?

like image 510
Montaner Avatar asked Feb 06 '19 10:02

Montaner


People also ask

Does derived class inherit assignment operator?

In C++, like other functions, assignment operator function is inherited in derived class.

Is assignment operator automatically generated?

It is well-known what the automatically-generated assignment operator will do - that's defined as part of the standard and a standards-compliant C++ compiler will always generate a correctly-behaving assignment operator (if it didn't, then it would not be a standards-compliant compiler).

What does the derived class have access to?

A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class. Constructors, destructors and copy constructors of the base class.


1 Answers

Every class has at least one assignment operator implicitly defined when we don't provide one ourselves.

And when a member function in a derived class is defined with the same name as a member in the base class, it hides all the base class definitions for that name.

You can use a using declaration, but be warned that it will pull all the members named operator= and allow code like this:

A a; B b; b = a; 

Which is slightly dubious.

like image 184
StoryTeller - Unslander Monica Avatar answered Sep 29 '22 17:09

StoryTeller - Unslander Monica