Virtual/pure virtual explained

后端 未结 12 1472
暖寄归人
暖寄归人 2020-11-22 01:31

What exactly does it mean if a function is defined as virtual and is that the same as pure virtual?

12条回答
  •  故里飘歌
    2020-11-22 02:28

    Pure Virtual Function

    try this code

    #include 
    using namespace std;
    class aClassWithPureVirtualFunction
    {
    
    public:
    
        virtual void sayHellow()=0;
    
    };
    
    class anotherClass:aClassWithPureVirtualFunction
    {
    
    public:
    
        void sayHellow()
        {
    
            cout<<"hellow World";
        }
    
    };
    int main()
    {
        //aClassWithPureVirtualFunction virtualObject;
        /*
         This not possible to create object of a class that contain pure virtual function
        */
        anotherClass object;
        object.sayHellow();
    }
    

    In class anotherClass remove the function sayHellow and run the code. you will get error!Because when a class contain a pure virtual function, no object can be created from that class and it is inherited then its derived class must implement that function.

    Virtual function

    try another code

    #include 
    using namespace std;
    class aClassWithPureVirtualFunction
    {
    
    public:
    
        virtual void sayHellow()
        {
            cout<<"from base\n";
        }
    
    };
    
    class anotherClass:public aClassWithPureVirtualFunction
    {
    
    public:
    
        void sayHellow()
        {
    
            cout<<"from derived \n";
        }
    
    };
    int main()
    {
        aClassWithPureVirtualFunction *baseObject=new aClassWithPureVirtualFunction;
        baseObject->sayHellow();///call base one
    
        baseObject=new anotherClass;
        baseObject->sayHellow();////call the derived one!
    
    }
    

    Here the sayHellow function is marked as virtual in base class.It say the compiler that try searching the function in derived class and implement the function.If not found then execute the base one.Thanks

提交回复
热议问题