简体   繁体   中英

How to call a derived class' virtual function from the base class in C++

I have:

class A
{
public:
    virtual some_type foo();
protected:
    virtual some_type bar();
}

class B : public A
{
protected:
    some_type bar() override;
}

// std::shared_ptr<B> b_ptr;
b_ptr->foo();

Where A::foo calls bar . For some reason that I cannot seem to understand, A::bar is being called insted of B::bar . Is there any way to ensure B::bar is called instead?

EDIT:

some_type A::foo() {
    this->bar();
}

EDIT 2: Class was instantiated as A, and then cast to B, hence the shared pointer to B was invalid.

It depends.

If foo() calls bar() in this way:

some_type foo(){ A::bar(); }

This is compile time binding, and so the compiler will bind that call to A::bar() even if the dynamic type is B .

Instead, if foo() calls bar() in this way:

some_type foo(){ this->bar(); /*or just bar(), same thing*/}

Then because bar() is virtual, the binding will be resolved at runtime, and so it will call the bar() function for the dynamic type, thus B::bar() .

So this code:

class A
{
public:
    virtual void foo(){this->bar();};
protected:
    virtual void bar(){cout<<"A";};
};

class B : public A
{
protected:
    void bar() override{cout<<"B";};
};

int main() {
    std::shared_ptr<B> b_ptr(new B);
    b_ptr->foo(); // B
}

Will print B , but this code:

class A
{
public:
    virtual void foo(){A::bar();};
protected:
    virtual void bar(){cout<<"A";};
};

class B : public A
{
protected:
    void bar() override{cout<<"B";};
};

int main() {
    std::shared_ptr<B> b_ptr(new B);
    b_ptr->foo(); // A
}

will print A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM