0

So basically, in this code I create interface (abstract class) and then derived from it.

struct IPrintable
{
    virtual void Print() = 0;
};

struct Base : public IPrintable
{
    void Print()
    {
        std::cout << "Print from Base\n";
    }
};

//And another class after that
struct A_Struct : public Base
{

};

After that in main function I create A_Struct and 3 pointer to it :

int main()
{
A_Struct myA;

IPrintable* Printp = &myA;
Base* Basep = &myA;
A_Struct* Ap = &myA;

//And of course we calling Print method
Printp->Print();
Basep->Print();
Ap->Print();

system("Pause");
return 0;
}

And everything is fine. BUT if we have need to add another case of Print just to A_Struct like so:

struct A_Struct : public Base
{
    void Print(int myI)
    {
        std::cout << "Print num : " << myI << " from A_Struct\n";
    }
};

The program will say "'A_Struct::Print': function does not take 0 arguments", which is mean that compiler can't find function Print().

We can fix this error by casting Ap pointer to IPrintable* like so:

((IPrintable*)Ap)->Print();

And everything will be fine again. But my question is: Why does this error even appear? Why it can't find overridden function by default?

Vlad
  • 113
  • 2
  • 9

0 Answers0