I’ve just tried this piece of code:
struct FaceOfPast
{
virtual void Smile() = 0;
};
struct FaceOfFuture
{
virtual void Smile() = 0;
};
struct Janus : public FaceOfPast, public FaceOfFuture
{
virtual void Smile() {printf(":) ");}
};
…
void main()
{
Janus* j = new Janus();
FaceOfFuture* future = j;
FaceOfPast* past = j;
future->Smile();
past->Smile();
delete j;
}
It works as intended (outputs two smiley faces), but I don’t think it should even compile, redeclaration of Smile() in Janus being ambiguous.
How (and why) does it work?
There’s no ambiguity because you call
Smile()on pointers toFaceOfFutureandFaceOfPastthat only declare one methodSmile().Because calling the method on a base class pointer can’t result in an ambiguity, let’s treat the situations when you call the method directly on the child class pointer:
The derived class, besides overriding, also hides the base classes’ declaration of
Smile(). You’d have an ambiguity only if you wouldn’t be overriding the method in your derived class:The following compiles:
Although you call
Smileon aJanus, the base class declarations are hidden.The following doesn’t:
Because of the ambiguity.