Example:
class C
{
public:
void operator =(int i) {}
};
class SubC : public C
{
};
The following gives compilation error:
SubC subC;
subC = 0;
"no match for 'operator=' in 'subC = 0'"
Some sources state that it is because assignment operators are not inherited. But isn't it simply because default constructed copy-assignment of SubC
overshadows them?
- Quora Why can’t you assign a base class object to a derived class reference type? First thing you should remember is that the methods are called on object and not the reference. Now coming to your question, lets suppose there is only one method in Animal class named “sleep ( )”.
It assigns the members of class X if it has any, but it won’t assign the members of the derived classes. What’s a C++ programmer to do? We’re going to see several solutions.
We need to provide an implementation in X for this virtual operator= as the operator= in derived classes call their base classes’, and the fact that we declare it virtual prevents the compiler to generate it for us. Unless X has complicated data members, we can write this: Then in the base classes, we implement this virtual operator=.
That means, we can conclude that- if we are using base pointer to derived objects, then we should publicly inherit the base class to derived class (Not in private or protected mode). Correct..? … Download, Vote, Comment, Publish.
The copy assignment operator is automatically generated in the derived class. This causes the base class's assignment operator to be hidden due to the regular name hiding rules of C++. You can unhide the name in the base class through the "using" directive. For example:
class C
{
public:
void operator =(int i) {}
};
class SubC : public C
{
public:
using C::operator=;
};
A copy assignment operator for a base class does not have the signature required for a copy assignment operator for a derived class. It is inherited by the derived class, but does not constitute a copy assignment operator in it. So even though assignment operators are inherited, just like other member functions, it does not provide copy assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With