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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With