An overloaded statement =declared as protected is publicly available for child classes that inherit the parent class as public.
#include <iostream>
class A {
public:
A(char c) : i(c) {}
char i;
protected:
A& operator=(const A& rdm) {
std::cout << "accessing operator=()" << std::endl;
i = 'x';
return *this;
}
};
class B : public A {
public:
B(char c) : A(c) {}
};
int main(int ac, char** av) {
B a('a');
B b('b');
std::cout << "a.i == " << a.i << std::endl;
a = b;
std::cout << "a.i == "<< a.i << std::endl;
}
Compilation error:
$ g++ -Wall -o test_operator ~/test_operator.cpp
$ ./test_operator
a.i == a
accessing operator=()
a.i == x
Using A is not directly compiled. Any other operator overload than operator=()will not compile. Tested with g ++ 4.4.7 and 7.3.0 with both C ++ 98 and C ++ 17.
Why is it operator=()publicly available in this case?
source
share