Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assignment operators of parent class are not accessible from derived class objects

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?

like image 460
mip Avatar asked Apr 09 '12 00:04

mip


People also ask

Why can’t you assign a base class object to a derived class?

- 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 ( )”.

Does it assign the members of a derived class to X?

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.

How to implement the virtual operator= in derived classes?

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=.

Should we inherit the base class to the derived class?

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.


2 Answers

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=;
};
like image 172
Vaughn Cato Avatar answered Sep 22 '22 00:09

Vaughn Cato


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.

like image 43
Bhavya Avatar answered Sep 20 '22 00:09

Bhavya