+ 3

What is the use of virtual function?

I don't know why and how I should use it....can someone explain in simple terms? (without using complicated formal book definitions 😒)

15th Dec 2016, 9:41 AM
Towfique Kabir
Towfique Kabir - avatar
1 Answer
+ 5
If you declare a function as virtual, for example: class Car { public : virtual void drive() {cout<<"Car drives";}} ; Then derived classes can override (replace) this function with their own version: class BMW : public Car { public : virtual void drive() {cout<<"Bmw drives";}} ; Repeat this process for other types of car. The cool thing is you can now go : Car* cars[] = {new Bmw, new Audi, new Ford,..etc..} ; And you an treat all the different cars as just a collection of cars, like this: for(int i=0; i < N; i++) cars[i]->drive() ; And will print to cout : BMW drives Audi drives Ford drives ..etc.. Note that the cars pointer call in the for loop to drive() does not call the Car::drive() function (to output "Car drives") , but the same function in the derived class, which outputs its own version. This is called polymorphism and is enabled by the virtual keyword.
15th Dec 2016, 10:21 AM
Ettienne Gilbert
Ettienne Gilbert - avatar