Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual Functions in C++ and Java

I have been reading about Virtual functions and found,

VF are used in polymorphism of an inherited class.

So , if a class and derived class both have the same function name, VF binds the appropriate function to the function call.

i.e. If the function in question is designated virtual in the base class then the derived class's function would be called. If it is not virtual, the base class's function would be called.

In Java by default: all functions are Virtual C++: Non-virtual and can be made Virtual in Java by using final, private access modifier while in C++ using Virtual keyword to make a function virtual.

Based on the above theory, i wrote the code:

#include <iostream>

class base{
    public : 
        virtual void function1(){
            std::cout<<"BaseVirtual"<<std::endl;
        }

        void function2(){
            std::cout<<"Base NonVirtual"<<std::endl;
        }
};


class derieved: public base
{
    public : 
        void function1(){
            std::cout<<"Derieved Virtual"<<std::endl;
        }

        void function2(){
            std::cout<<"Derieved NonVirtual"<<std::endl;
        }
};



int main()
{
    base b1;
    derieved d1;

    b1.function1();
    b1.function2();

    d1.function1();
    d1.function2();    

}

Now based on the fact, if its a virtual function then only derived class function is called, my output for the above program should be:

BaseVirtual
Base NonVirtual
Derieved Virtual
Base NonVirtual

however, it came out to be:

BaseVirtual
Base NonVirtual
Derieved Virtual
Derieved NonVirtual

which must be right of course. So my question is the output totally violates the statement If the function in question is designated virtual in the base class then the derived class's function would be called. If it is not virtual, the base class's function would be called. for the call:

  d1.function2();    
like image 608
CodeMonkey Avatar asked Dec 09 '22 20:12

CodeMonkey


1 Answers

Yes.. the role of virtual comes into picture if and only if you have are trying to access the derived class object with a base class pointer.

With you example:-

#include <iostream>

class base{
    public : 
        virtual void function1(){
            std::cout<<"BaseVirtual"<<std::endl;
        }

        void function2(){
            std::cout<<"Base NonVirtual"<<std::endl;
        }
};


class derieved: public base
{
    public : 
        void function1(){
            std::cout<<"Derieved Virtual"<<std::endl;
        }

        void function2(){
            std::cout<<"Derieved NonVirtual"<<std::endl;
        }
};



int main()
{
    base *b1;
    derieved d1;

    b1=&d1;

    b1->function1();
    b1->function2();    
    return 0;
}

output:-

Derieved Virtual
Base NonVirtual
like image 168
dead programmer Avatar answered Dec 24 '22 13:12

dead programmer