Call derived class method from base class instance



I am trying to use polymorphism, to call derived "add" method from base class instance.

But it still want's to run base class RealThing "add" method.

I was expecting derived class RealThingNextVersion "add" method.

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

class VirtualObject
    virtual void load() {
        cout << "Nothing to load." << endl;

    void import(string file) {
        //here some importing stuff

class RealThing :public VirtualObject
    string file;

    int id;

    RealThing(string fileName = "data.txt") { file = fileName; }

    void load() {
        cout << "Thing data loaded." << endl;

    virtual void add(int id) {
        cout << "Added V1: " << id << endl;

class RealThingNextVersion : public RealThing
    string desc;

    virtual void add(int id, string desc) {
        cout << "Added V2: " << id << " with description " << desc <<  endl;

int main() {
    RealThing rt;
    RealThingNextVersion rtv;

    RealThing* r;
    r = &rt;
    r->load(); // OK., returns: Thing data loaded.
    r->add(11); // OK., returns: Added V1: ...

    r = &rtv;
    r->add(22, "info"); // Here "Error: too many arguments in function call" 
    // it still want's to run RealThing "add",
    // and I was expecting RealThingNextVersion "add"


1 Answer: 

The add in RealThingNextVersion has a different call signature (different parameters) from the one in RealThing, so it is a different function and not an override of add. If you add the override keyword in your function declaration

virtual void add(int id, string desc) override;

with a recent compiler the compiler will tell you that you're not overriding anything.