Why parent class assignment operators are not available from derived class objects

Example:

class C { public: void operator =(int i) {} }; class SubC : public C { }; 

The following is a compilation error:

 SubC subC; subC = 0; 

"no match for 'operator =' in 'subC = 0'"

Some sources claim this is because assignment operations are not inherited. But isn't it just because the default SubC -copy-assignment of SubC overshadows them?

+6
source share
4 answers

A copy assignment operator is automatically generated in a derived class. This causes the base class assignment operator to be hidden due to the usual C ++ name hiding rules. You can display the name in the base class using the using directive. For instance:

 class C { public: void operator =(int i) {} }; class SubC : public C { public: using C::operator=; }; 
+11
source

The copy assignment operator for the base class does not have the signature required for the copy assignment operator for the derived class. It is inherited by a derived class, but is not a copy assignment operator in it. Therefore, even if assignment operators are inherited, like other member functions, it does not provide copy assignment.

+2
source

I did not do this, but according to The Man Himself (Stroustrup) it is a feature of C ++ 11 to do this with constructors, but it has been since C ++ 98 did it using other methods.

This is DIRECTLY taken from the link:

People are sometimes confused by the fact that the usual field rules apply to class members. In particular, a member of a base class is not to the same extent as a member of a derived class:

 struct B { void f(double); }; struct D : B { void f(int); }; B b; bf(4.5); // fine D d; df(4.5); // surprise: calls f(int) with argument 4 

In C ++ 98, we can "raise" a set of overloaded functions from a base class to a derived class:

 struct B { void f(double); }; struct D : B { using B::f; // bring all f()s from B into scope void f(int); // add a new f() }; B b; bf(4.5); // fine D d; df(4.5); // fine: calls D::f(double) which is B::f(double) 

So, I will go. You can probably β€œtake it if you want,” even before C ++ 11, although I have not tried it myself.

+1
source

With the exception of the copy assignment statement, another overloaded statement can be inherited.

I agree that the default copy-assignment of SubC overshadows the overloaded C assignment operator.

If SubC does not provide a copy assignment operator, the compiler will perform the copy operation as follows:

 class SubC : public C { public: SubC & operator=( const SubC & other ); } 

then "SubC and operator = (const SubC, etc.)" overlap the assignment operator C, leading to a compilation error.

If

 SubC other; SubC subC; subC = other; 

then, this case, compile ok.

0
source

Source: https://habr.com/ru/post/912705/


All Articles