Why do we need virtual functions in C++?

前端 未结 26 3117
北恋
北恋 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 05:59

    Why do we need virtual functions?

    Virtual functions avoid unnecessary typecasting problem, and some of us can debate that why do we need virtual functions when we can use derived class pointer to call the function specific in derived class!the answer is - it nullifies the whole idea of inheritance in large system development, where having single pointer base class object is much desired.

    Let's compare below two simple programs to understand the importance of virtual functions:

    Program without virtual functions:

    #include 
    using namespace std;
    
    class father
    {
        public: void get_age() {cout << "Fathers age is 50 years" << endl;}
    };
    
    class son: public father
    {
        public : void get_age() { cout << "son`s age is 26 years" << endl;}
    };
    
    int main(){
        father *p_father = new father;
        son *p_son = new son;
    
        p_father->get_age();
        p_father = p_son;
        p_father->get_age();
        p_son->get_age();
        return 0;
    }
    

    OUTPUT:

    Fathers age is 50 years
    Fathers age is 50 years
    son`s age is 26 years
    

    Program with virtual function:

    #include 
    using namespace std;
    
    class father
    {
        public:
            virtual void get_age() {cout << "Fathers age is 50 years" << endl;}
    };
    
    class son: public father
    {
        public : void get_age() { cout << "son`s age is 26 years" << endl;}
    };
    
    int main(){
        father *p_father = new father;
        son *p_son = new son;
    
        p_father->get_age();
        p_father = p_son;
        p_father->get_age();
        p_son->get_age();
        return 0;
    }
    

    OUTPUT:

    Fathers age is 50 years
    son`s age is 26 years
    son`s age is 26 years
    

    By closely analyzing both the outputs one can understand the importance of virtual functions.

提交回复
热议问题