1

I have a class structure looking like this:

class A {
public:
     A();

     virtual void doSomething() {
         qDebug() << "Hello from class A";
     }
};

class B : public A {
public:
    B();

    void doSomething() {
        qDebug() << "Hello from class B";
    }
};

class C : public A {
public:
    C();

    void doSomething() {
        qDebug() << "Hello from class C";
    }
};

Somewhere else I have a method like this:

void doSomethingElse(const A argument = A()) {
    argument.doSomething();
}

Everytime doSomethingElse is called I get the "Hello from class A" output, even if I pass an instance of class B or C as the argument. What am I doing wrong here?

peppe
  • 21,934
  • 4
  • 55
  • 70
strnmn
  • 555
  • 1
  • 6
  • 30

1 Answers1

3

It needs to be passed by reference:

void doSomethingElse(const A& argument = A()) {
    argument.doSomething();
}

If you don't pass by reference, then the parameter becomes a copy of the argument, and only the A part of the argument is copied. doSomething() is then being called on an A, and not the object you originally passed as an argument.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132