I am confused regarding checking of access specifiers statically or dynamically. It is said that access specifiers are not checked dynamically. What does that mean ?
This example has been taken from different posts on SO. Consider this example
Example A:
class Base
{
public:
virtual void Message() = 0;
};
class Intermediate : public Base
{
//Is Message method virtual here too ? is it private or public ?
};
class Final : public Intermediate {
void Message() {
cout << "Hello World!" << endl;
}
};
Final final;
Now suppose I do something like this
Final* finalPtr = &final;
finalPtr->Message();
The above wont work and my understanding is that in Final class the Message Method is private. Is that correct ? If so why does this work ? the method in
Intermediate* finalPtr = &final; // or Base* finalPtr = &final;
finalPtr->Message();
Is the reason why the above code is working because the base class pointer is instantiated with a derived class. If so why does the call to Message() work. The post on SO states that since the inheritance is public hence it will be inherited as public function ? on the other hand the function itself in the class has the private access specifier (since by default its private in a class). I am confused here and I would appreciate if someone could clarify this. Would it be correct to say that if a base class is instantiated with a derived class. Then the access specifier of the base class method takes precedence over the access specifier of the derived class ?
Update :
Also I noticed that if I change the Intermediate
and Final
code to the following
class Intermediate : public Base
{
public: //Incase this public was absent then the following example wont work
void Message() {
cout << "Hello World! Intermediate" << endl;
}
};
class Final : public Intermediate {
void Message() {
cout << "Hello World! final" << endl;
}
};
and use it as such
Intermediate* i = new Final();
i->Message();
Then inorder to get the output "Hello World! final"
it is necessary to mark the interface method as public. Why is that ? The method Message
was inherited as public . Why do i need to mark it as public now ?