Why the inherited protected operator = () has public access

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?

+4
source share
1 answer

There Bis an implicit copy assignment operator with access public.

From C ++ 11 Standard :

, . , ; ([dcl.fct.def]). , . X

X& X::operator=(const X&)

- B of X , const B&, const volatile B& B

- X, M ( ), , const M&, const volatile M& M.

X& X::operator=(X&)

, , :

class B : public A {
public:
    B(char c) : A(c) {}
    B& operator=(B const& rhs) { A::operator==(rhs); return *this; }
};

​​ , . , B A .

#include <iostream>

class A {
public:
    A(char c) : i(c) {}
    char i;

protected:
    A& operator=(const A& rdm) {
        std::cout << "accessing A::operator=()" << std::endl;
        i = 'x';
        return *this;
    }
};

class X
{
   public:
      X& operator=(X const& rhs)
      {
        std::cout << "accessing X::operator=()" << std::endl;
        return *this;
      }
};

class B : public A {
public:
    B(char c) : A(c) {}
    X x;
};


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;
}

:

a.i == a
accessing A::operator=()
accessing X::operator=()
a.i == x

/ , :

B& operator=(B const& rhs)
{
   A::operator==(rhs);
   this.x = rhs.x;
   return *this;
}

, :

/ X / . X --, X , .

+6

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


All Articles