Please look at the following code listing:
#include <iostream>
using namespace std;
class Base {
public:
virtual void Message() = 0;
};
class Intermediate : public Base {
};
class Final : public Intermediate {
void Message() {
cout << "Hello World!" << endl;
}
};
int main() {
Final final;
/* Wont work (obviously):
Final* finalPtr = &final;
finalPtr->Message();
*/
// Works:
Intermediate* finalPtr = &final; // or Base* finalPtr = &final;
finalPtr->Message();
return 0;
}
Take note of the following:
- In the abstract Base class, the pure virtual function message() is public
- Intermediate class (also abstract) inherits from Base class (Does message() function remain public pure virtual in Intermediate?)
- Final class inherits from Intermediate class and message() function is private (by default)
- In main, an object of type Final is created
- An Intermediate pointer to the Final object is created
Question: If you run the program, the line finalPtr->Message(); successfully invokes Final's implementation of message() function though its private. How does that happen? Does a base class override or ignore a derived class' access restrictions?
Related Question: In relation to (2.) above, what is the right way to define Intermediate class? Does one need to re-declare the pure virtual function message() from the base class bearing in mind that Intermediate class is not intended to provide an implementation.
NOTE: Code was tested with both Digital Mars Compiler (dmc) and Microsoft's Visual Studio Compiler (cl) and works just fine in both