Why is the access qualifier not considered when overriding a virtual function?

After printing the code "I B!". This is a little strange because it B::foo()is closed. It A* ptrcan be said that its static type A( foois public), and its dynamic type B( foois private). Therefore, I can call foowith a pointer to A. But this way I have access to the private function in B. Could this be considered encapsulation violation?

Since the access qualifier is not part of the class signature, it can lead to such strange cases. Why is the C ++ access qualifier not taken into account when a virtual function is redefined? Can I ban such cases? What is the design principle behind this decision?

Live example .

#include <iostream>

class A
{
public:
    virtual void foo()
    {
        std::cout << "I'm A!\n";
    };
};

class B: public A
{
private:
    void foo() override
    {
        std::cout << "I'm B!\n";
    };
};

int main()
{
    A* ptr;
    B b;

    ptr = &b;

    ptr->foo();
}
+4
source share
2 answers

You have a few questions, so I will try to answer them one by one.

Why is the C ++ access qualifier not taken into account when redefining a virtual function?

Because access qualifiers are considered by the compiler after all overload permissions. This behavior is prescribed by the Standard.

, . cppreference:

: , .. . , .

, :

, , , -. .

. , .

?

.

, - , .

?

: "" . : .

, CoolClass,

class CoolClass {
public:
  void doCoolStuff(int coolId); // your class interface
private:
  void doCoolStuff(double coolValue); // auxiliary method used by the public one
};

, / . :

CoolClass cc;
cc.doCoolStuff(3.14); // invokes CoolClass::doCoolStuff(int)
  // yes, this would raise the warning, but it can be ignored or suppressed 

- , - "" . , CoolClass::doCoolStuff(double).

, , , " " . (. ).

?

. , : " B, A" - , " " ".

, , , ? , , .

. .

P.S.

, , . , , . . . , , .

P.P.S.... / . , , .

+2

, public, private .., , - .

, , private virtual? ?

?

, , .

( ), public virtual private .

+1

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


All Articles