How can a derived class use a protected member of the base class?

Let's say that the base class Adefines a protected member. A derived class Buses this member.

class A
{
public:
  A(int v) : value(v) { }

protected:
  int value;
};

class B : public A
{
public:
  B(int v) : A(v) { }
  void print() const;
  void compare_and_print(const A& other) const;
};

The function B::printsimply takes the value of the current element and prints it:

void B::print() const
{
  std::cout << "Value: " << value << "\n";
}

Another member function B::compare_and_printtakes an instance A, checks their values ​​and prints a maximum of both:

void B::compare_and_print(const A& other) const
{
  auto max_value = std::max(value, other.value);
  std::cout << "Max value: " << max_value << "\n";
}

If it otherwas an instance of a class B, this is not a problem. But the function would like to work with any instances A. This, unfortunately, does not compile. Here is what Klang says about it:

test.cpp:27:42: error: 'value' is a protected member of 'A'
  auto max_value = std::max(value, other.value);
                                         ^
test.cpp:9:7: note: can only access this member on an object of type 'B'
  int value;
      ^
1 error generated.

This limitation sounds counter-intuitive to me. However, I am not going to dispute the C ++ standard about this (I'm still interested in justifying this decision).

, : , .

, , - - , . , .

API?


EDIT: :

, , - , ( , , , ).

, , .

+4
2

( , ):

void B::compare_and_print(const A& other) const
{
  auto max_value = std::max(value, other.*(&B::value));
  std::cout << "Max value: " << max_value << "\n";
}
+3

:

struct A_Helper : public A
{
    static int GetProtectedValue(const A & a)
    {
        return static_cast<const A_Helper&>(a).Value;
    }
};

, A_Helper::GetProtectedValue(a)

other const B& ( static_cast reinterpret_cast), , other B. , , , other B , / "" .

, B memeber value_B other C. static_cast<const B&>(other).value_B - Undefined .

0

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


All Articles