Calling a virtual function in a subclass from a superclass

I know that this question must have been covered endlessly many times, but I have looked for the previous questions and nothing seems to pop.

This is about inheritance and virtual functions in C ++. I have a problem with calling virtual functions in subclasses from a superclass.

Let me give you an example. Start with three classes that inherit from each other.

class A {

    void foo() { bar() }
    virtual void bar() { }

};

class B : public A {

    virtual void bar() { }

};

class C : public B {

    virtual void bar() { // do something }

};

Now I want the variable to be declared as B *, but to be created as C *.

B* myObject = new C();
myObject->foo();

When I do this and call foo () on myObject, then A :: foo () calls bar (). But only B :: bar () is called, not C :: Bar () - which is actually myObject, although it is declared as B, which again affects the fact that "// does nothing" is not executed.

How do I tell A :: foo () that it should look at the lowest implementation?

?

//

EDIT:

C:: Foo . Foo A, , . , A: Foo Bar(). B: Bar, C:: Bar.

, , void * A.

:

void A:Foo(void *a) {

    A* tmpA = static_cast<A*> (a);
    tmpA->bar();

}

, tmpA A. - , B *, B:: Bar, tmpA C *, C:: Bar.

+5
6

"A:: foo C:: bar", . - ? B::bar , C - . C::bar B::bar, B::bar(); .

#include <iostream>
using namespace std;

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

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

class C : public B {
public:
    virtual void bar() { cout << "C::bar" << endl; }
};

int main()
{
    B* c = new C();
    c->foo();
    return 0;
}
+5
void A:Foo(void *a) {

    A* tmpA = static_cast<A*> (a);
    tmpA->bar();

}

undefined. B * void *, void * A *. , , *. , dynamic_cast.

+2

, :

B* variable = new C();
variable->foo();

C:: Foo .

( , C:: Foo - std::cout << "Hi mom!" << std::endl;)

0

:

B* myObject = new C();
myObject->foo(); // not variable->foo()

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

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

class C : public B
{
public:
    virtual void bar() { std::cout << "C"; }
};

'C', .

0

.

B:: bar(), C:: Bar()

. C, , vtable bar() C:: bar(), foo() C:: bar().

A:: foo() A, ,

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

?

0

? Visual Studio (IIRC) , , , - ?

0

All Articles