0

I am trying to comprehend virtual functions. How so I make my put() function virtual? What changes does that necessitate in the code?

#include <iostream>
#include <string>
using namespace std;

class Circle
{
public:
    Circle(double radius) {this->radius = radius; }
    void put() const {cout << "Radius = " << radius;}
private:
    double radius;
};

class ColoredCircle: public Circle
{
public:
    ColoredCircle(double radius, string color);
    void put() const;
private:
    string color;
};

ColoredCircle::ColoredCircle(double radius, string color)
    : Circle(radius), color(color) {}

void ColoredCircle::put() const
{
    Circle::put();
    cout << " Color = " << color;
}

int main()
{
    ColoredCircle redCircle(100., "red");
    Circle* circle1 = &redCircle;
    circle1->put();
    cout << endl;
    Circle circle(50.);
    Circle* circle2 = &circle;
    circle2->put();
    cout << endl;
    std::cin.get();
    return 0;
}
David Tunnell
  • 7,252
  • 20
  • 66
  • 124

1 Answers1

1

You just have to write the virtual keyword in front of the function in the base class :

class Circle
{
public:
    Circle(double radius) {this->radius = radius; }
    virtual void put() const {cout << "Radius = " << radius;}
//  ^^^^^^^
private:
    double radius;
};

But you should understand the case where the virtual functions are used. What is the performances cost, why it is useful, etc ...

A little piece of answer : A virtual method is a special of method whose the behavior can be overriden within an inheriting class with amethod of the same signature.

About the performance cost : There is definitely measurable overhead when calling a virtual function - the call must use the vtable to resolve the address of the function for that type of object. The extra instructions are the least of your worries. Not only do vtables prevent many potential compiler optimizations, they can also thrash your I-Cache.

Of course whether these penalties are significant or not depends on your application, how often those code paths are executed, and your inheritance patterns.

I would suggest you to read some articles about virtual functions, here is a non exhaustive list :

Community
  • 1
  • 1
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62