3

i need to call the overidden function inside B class through C class but it gives "Base" as a output rather than "Derived". when I call this code part classC.getTargetB().example(); i need to get "Derived" as a output. how can i reach my goal in the code.

class A {

public:
    A() {};
    virtual void example() { std::cout << "Base" << std::endl; }
};
class B :public A {

protected:
    std::string name;

public:
    B() {};
    B(std::string n) { name = n; }
    void example() override { std::cout << "Derived" << std::endl; }
};
class C {
protected:
    std::vector<std::shared_ptr<A>> ptr;

    std::shared_ptr<A> targetBobject;

public:
    void setB(std::shared_ptr<A> target) {
        targetBobject = target;
    }
    A getTargetB() {
        return *targetBobject;
    }
};
int main()
{
    A example;

    std::vector<std::shared_ptr<A>> parent;

    C classC;

    std::shared_ptr<B> ptr1 = std::make_shared<B>("B1");
    std::shared_ptr<B> ptr2 = std::make_shared<B>("B2");

    parent.push_back(std::move(ptr1));
    parent.push_back(std::move(ptr2));


    //parent.at(0)->example(); this gives 'Derived' as a output

    classC.setB(parent.at(0));
    classC.getTargetB().example();// gives 'Base' as a output
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
wdafoe666
  • 109
  • 9

0 Answers0