Click here to Skip to main content
15,885,869 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
What is the use of making virtual function and why we can not make any function as virtual?
Posted

As an example say you have a class called Shape and you have a function CalculateArea. Not all shapes will calculate the area in the same way so in your base class you would;

class Shape
{
    public:
        virtual double CalculateArea() { width * height; }
} 


Then in your derived class you would;

class Circle : Shape
{
    public:
        virtual double CalculateArea() { pi * radius * radius; }
}


You only make functions virtual where it makes sense.
 
Share this answer
 
Virtual Functions are the basis for "polymorphism", you should look that up or ask your instructor why polymorphism is important in OOP.

There is nothing from stopping you from declaring *every functions* to be virtual but, depending on the compiler, the object instantiation will be larger for each function so declared.
 
Share this answer
 
In brief: because they are two different things.

In longer, consider this, and look how say_hello and say_vhello behave respet to A*.


#include <iostream>

class A
{
public:
    virtual void vhello() 
    { std::cout << "I'm A::vhello" << styd::edl; }
    
    void hello() 
    { std::cout << "I'm A::hello" << styd::edl; }
};

class B: public A
{
public:
    virtual void vhello() 
    { std::cout << "I'm B::vhello" << styd::edl; }
    
    void hello() 
    { std::cout << "I'm B::hello" << styd::edl; }
};

void say_hello(A* pa)
{ pa->hello(); }

void say_vhello(A* pa)
{ pa->vhello(); }

int main()
{
    A a;
    B b;    // remebre B <b>is a</b> A
    
    say_hello(&a);   //call A::hello
    say_hello(&b);   //convert B* to A*, call A::hello
    
    say_vhello(&a);  //seek vtable for vhello, call A::vhello 
    say_vhello(&b);  //convert B* to A*, seek vtable for vhello, call B::vhello
    
    return 0; 
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900