Why do we need virtual functions in C++?

前端 未结 26 3180
北恋
北恋 2020-11-21 05:50

I\'m learning C++ and I\'m just getting into virtual functions.

From what I\'ve read (in the book and online), virtual functions are functions in the base class that

26条回答
  •  梦如初夏
    2020-11-21 06:02

    Need for Virtual Function explained [Easy to understand]

    #include
    
    using namespace std;
    
    class A{
    public: 
            void show(){
            cout << " Hello from Class A";
        }
    };
    
    class B :public A{
    public:
         void show(){
            cout << " Hello from Class B";
        }
    };
    
    
    int main(){
    
        A *a1 = new B; // Create a base class pointer and assign address of derived object.
        a1->show();
    
    }
    

    Output will be:

    Hello from Class A.
    

    But with virtual function:

    #include
    
    using namespace std;
    
    class A{
    public:
        virtual void show(){
            cout << " Hello from Class A";
        }
    };
    
    class B :public A{
    public:
        virtual void show(){
            cout << " Hello from Class B";
        }
    };
    
    
    int main(){
    
        A *a1 = new B;
        a1->show();
    
    }
    

    Output will be:

    Hello from Class B.
    

    Hence with virtual function you can achieve runtime polymorphism.

提交回复
热议问题