0

Why does the compiler not throw error in main() for p->f4(); line. As per my understanding class B hides f4() and should throw error

class A
{
    public:
        void f1(){}
        virtual void f2(){}
        virtual void f3(){}
        virtual void f4(){}
};

class B : public A
{
    public:
        void f1(){}
        void f2(){}
        void f4(int x){}
};


int main()
{
    A *p;
    B o2;
    p = &o2;
    
    p->f1();
    p->f2();
    p->f3();
    p->f4();  //why doesn't it throw an error for this line as class B hides f4()
    p->f4(5);  
    
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

2

The static type of the pointer p is A *. So for this call

p->f4();

the function f4 is searched in the scope of the class A and is found and called. As the function is declared as virtual then if it would be overridden in the class B then the overriding function in the class B would be called.

But for this call

p->f4(5);

the compiler should issue an error because within the class A there is no function with the name f4 that accepts an argument of the type int.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335