Inheritance and Assignment Operators
I was doing some experiments with inheritance, and came across something a bit odd.
I have a base class in which the assignment operator is declared private, and is undefined. All member fields are protected, and thus accessible to derived classes.
The derived class adds no new fields. It simply exists to extend the functionality of the base class.
Since the derived class contains no new fields, in theory it should be able to define its assignment operator like this:
However, when I tried this, with gcc 4.0.1 on a Mac, anytime I tried to use the assignment operator with the derived class, the compiler would try to use the undefined base class assignment operator. And since this function did not exist, an error would be generated.
Making the base class operator a protected pure virtual function did not alleviate the error.
What finally made the error go away was adding in another assignment operator in the derived class:
Now everything works as expected.
As a side note, I realize that simply declaring the assignment operator in the base class, and making it protected will allow the derived class to use it. However, I was wondering about the behavior. Am I forgetting some silly rule of inheritance?
I have a base class in which the assignment operator is declared private, and is undefined. All member fields are protected, and thus accessible to derived classes.
The derived class adds no new fields. It simply exists to extend the functionality of the base class.
Since the derived class contains no new fields, in theory it should be able to define its assignment operator like this:
derived& derived::operator = (const base &rt);
However, when I tried this, with gcc 4.0.1 on a Mac, anytime I tried to use the assignment operator with the derived class, the compiler would try to use the undefined base class assignment operator. And since this function did not exist, an error would be generated.
Making the base class operator a protected pure virtual function did not alleviate the error.
What finally made the error go away was adding in another assignment operator in the derived class:
derived& derived::operator = (const derived &rt);
Now everything works as expected.
As a side note, I realize that simply declaring the assignment operator in the base class, and making it protected will allow the derived class to use it. However, I was wondering about the behavior. Am I forgetting some silly rule of inheritance?
| This one does not compile | This one compiles / works. I am curious as to why adding the extra assignment operator helps. | This one also compiles / works, which is unsurprising, since this is the standard way to do it. |
|
|
|
