Polymorphism and data hiding: Does a base class override or ignore a derived class' access restrictions?

前端 未结 2 1832
情话喂你
情话喂你 2021-01-14 16:32

Please look at the following code listing:

#include 

using namespace std;

class Base {
public:
    virtual void Message() = 0;
};

class In         


        
2条回答
  •  野的像风
    2021-01-14 17:00

    How does that happen? Does a base class override or ignore a derived class' access restrictions?

    With Public Inheritance all public members of the Base class become public members of the derived class. So Yes Message() is public function in Intermediate.

    The function is called on a base class(Intermediate) pointer the function is public in base class. The dynamic dispatch(i.e the actual call to Derived class function) only happens at runtime hence this works.

    The above is due to the fact that at runtime, the access specifiers have no meaning, the access specifier rules are resolved and effective only at compile time.

    If you call the function on the derived class pointer then at compile time the compiler detects that Message() is declared private in Final and hence it gives the error.


    While deriving from an Abstract class, the derived class MUST provide definition for ALL the Pure virtual functions of the Base class, Failing to do so will result in the Derived class also being an Abstract class.

    Here Intermediate class is an Abstract class and as long as you do not need to create objects of this class, it will work fine. Note that you can create a pointer to an Abstract class.

提交回复
热议问题