Why do we need virtual functions in C++?

前端 未结 26 3102
北恋
北恋 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

    You need at least 1 level of inheritance and an upcast to demonstrate it. Here is a very simple example:

    class Animal
    {        
        public: 
          // turn the following virtual modifier on/off to see what happens
          //virtual   
          std::string Says() { return "?"; }  
    };
    
    class Dog: public Animal
    {
        public: std::string Says() { return "Woof"; }
    };
    
    void test()
    {
        Dog* d = new Dog();
        Animal* a = d;       // refer to Dog instance with Animal pointer
    
        std::cout << d->Says();   // always Woof
        std::cout << a->Says();   // Woof or ?, depends on virtual
    }
    
    0 讨论(0)
  • 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 <iostream>
    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 <iostream>
    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.

    0 讨论(0)
  • 2020-11-21 06:00

    The keyword virtual tells the compiler it should not perform early binding. Instead, it should automatically install all the mechanisms necessary to perform late binding. To accomplish this, the typical compiler1 creates a single table (called the VTABLE) for each class that contains virtual functions.The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions,it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. When you make a virtual function call through a base-class pointer the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the correct function and causing late binding to take place.

    More details in this link http://cplusplusinterviews.blogspot.sg/2015/04/virtual-mechanism.html

    0 讨论(0)
  • 2020-11-21 06:01

    You have to distinguish between overriding and overloading. Without the virtual keyword you only overload a method of a base class. This means nothing but hiding. Let's say you have a base class Base and a derived class Specialized which both implement void foo(). Now you have a pointer to Base pointing to an instance of Specialized. When you call foo() on it you can observe the difference that virtual makes: If the method is virtual, the implementation of Specialized will be used, if it is missing, the version from Base will be chosen. It is best practice to never overload methods from a base class. Making a method non-virtual is the way of its author to tell you that its extension in subclasses is not intended.

    0 讨论(0)
  • 2020-11-21 06:02

    Need for Virtual Function explained [Easy to understand]

    #include<iostream>
    
    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<iostream>
    
    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.

    0 讨论(0)
  • 2020-11-21 06:02

    i think you are referring to the fact once a method is declared virtual you don't need to use the 'virtual' keyword in overrides.

    class Base { virtual void foo(); };
    
    class Derived : Base 
    { 
      void foo(); // this is overriding Base::foo
    };
    

    If you don't use 'virtual' in Base's foo declaration then Derived's foo would just be shadowing it.

    0 讨论(0)
提交回复
热议问题