1

I have the following Code:

class Base {
public:
    virtual std::string name() {
        return "Base";
    }
};

class B : public Base {
public:
    virtual std::string name() {
        return "B";
    }
};

class A : public Base {
public:
    Base base;
    A(Base &base) : base(base) {
        std::cout << base.name() << "\n";
    }
};

int main() {
    Base a = B();
    Base r = A(a);
}

The output is "Base", what do I have to change to get the Output "B" and why?

Holt
  • 36,600
  • 7
  • 92
  • 139
flo
  • 31
  • 1
  • 5
    Using polymorphism requires the use of pointers or references, your code performs object slicing – UnholySheep Nov 26 '21 at 14:10
  • @UnholySheep shouldn't a vtable be generated nonetheless? – DownloadPizza Nov 26 '21 at 14:13
  • 3
    @DownloadPizza that has nothing to do with the problem, `Base a = B();` creates an object that is of type `Base`, not type `B` - therefore any vtable lookup will find the function defined in `Base` – UnholySheep Nov 26 '21 at 14:16
  • Forget "vtable lookup"; that's an implementation detail. The type of `a` is `Base`, and calling `Base::name()` writes "Base". That's all there is to it. – Pete Becker Nov 26 '21 at 14:18
  • Thanks for your input. So I have to write Base *a = new B(); and Base r = A(*a); or is there a more elegant solution. – flo Nov 26 '21 at 14:22
  • 2
    @flo or `B b; A r(b);` – Caleth Nov 26 '21 at 14:30
  • Aside: did you really mean for `A` to have two `Base` subobjects? (one base class, and one data member) – Caleth Nov 26 '21 at 14:33

0 Answers0