0

so I have something that looks a bit like this:

 class A
{
public:
    A();
    virtual void yep();
private:

};

A::A()
{
}

void A::yep()
{
    std::cout << "A" << std::endl;
}

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

    void yep() override;
private:

};

B::B() : A()
{
}


void B::yep()
{
    std::cout << "B" << std::endl;
}

int main() {
std::vector<A> d;
    
A a = A();
A b = B();
A& c = b;

d.push_back(a);
d.push_back(c);

//for each
for (A i : d) {
    A& j = i;
    j.yep();
}
}
    

I'm expecting it to produce an output AB but instead, but I'm getting AA instead. Stepping through it lines by line in my code editor says it's executing the function of the superclass instead of the overridden one. Edit: So the thing with pointer/reference works and I've tried applying it to my implementation but it doesn't work. I've modified the example to look more like my implementation.

a SANCOON
  • 1
  • 1
  • You have 2 `A` objects `a` and `b`. The `b` variable is not a `B` – drescherjm Oct 17 '22 at 02:09
  • 1
    Polymorphism only works if you have a pointer or reference. You have neither. – Mark Ransom Oct 17 '22 at 02:13
  • You still have only `A` objects. `b` is of type `A` not `B` so are all the items in the vector. It does not matter in the places where you use a reference because the object slicing already happened and the objects are all `A` objects and none of them are `B` objects. – drescherjm Oct 17 '22 at 03:12
  • @drescherjm so would the solution to be make d a vector of A pointers instead of just A? I am making things of type B properly in my implementation. – a SANCOON Oct 17 '22 at 03:17
  • `std::vector) vec;` Here is a good example: [https://stackoverflow.com/a/44435425/487892](https://stackoverflow.com/a/44435425/487892) – drescherjm Oct 17 '22 at 03:59

0 Answers0