Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual functions in C++

In my C++ program:

#include<iostream.h>

class A
{
    public:
    virtual void func()
    {
         cout<<"In A"<<endl;
    }
};

class B:public A
{
    public:
    void func()
    {
        cout<<"In B"<<endl;
    }
};

class C:public B
{
    public:
    void func()
    { 
        cout<<"In C"<<endl;
    }
};  

int main()
{
    B *ptr=new C;
    ptr->func();
}

the statement should call B::func(). However, the function, C::func() is called. Please throw some light on this. Once the virtual keyword is removed in 'class A', this does not happen anymore.

like image 523
Avik Banerjee Avatar asked Mar 20 '26 06:03

Avik Banerjee


2 Answers

Once declared virtual function will be virtual in all derived classes (no matter if you explicitly specify it or not). So func() is virtual in A, B and C classes.

like image 154
begray Avatar answered Mar 22 '26 20:03

begray


For the basics you should read C++ FAQ Lite on Virtual Functions.

A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

like image 40
Marcin Gil Avatar answered Mar 22 '26 18:03

Marcin Gil