Reputation: 21
I have a very simple code that is using inheritance, and I have the same function prototype in my base and derived classes. I don't understand the last result (pB->bar()
), because I thought that since pB
points to a derived type object (after delete
) it should invoke D::bar()
.
#include <iostream>
class B {
public:
virtual void foo() { std::cout << "B:foo" << std::endl; }
void bar() { std::cout << "B:bar" << std::endl; }
};
class D : public B {
public:
virtual void foo() override { std::cout << "D:foo" << std::endl; }
void bar(){ std::cout << "D:bar" << std::endl;}
};
int main() {
B* pB = new B;
pB->foo();
pB->bar();
delete pB;
pB = new D;
pB->foo();
pB->bar();
delete pB;
}
the results of this are:
B:foo
B:bar
D:foo
B:bar
Upvotes: 2
Views: 198
Reputation: 596407
bar()
is not virtual
, so calls to it are resolved statically at compile-time using the type it is called on. It is not resolved dynamically at runtime, like you are expecting, similar to foo()
, which is virtual
.
Calling bar()
via a B*
pointer will call B::bar()
, and calling it via a D*
pointer will call D::bar()
instead. pB
is a B*
, so that is why pB->bar()
calls B::bar()
regardless of whether pB
points at a B
or D
object. It is a static call.
Upvotes: 0
Reputation: 168
The keyword virtual
creates a virtual table for the class function, then when you use a pointer to a class the program check the type of the class and try to find the function foo in the virtual table.
when you call bar the program check the class pointer for the implementation of bar and because the pointer is of type B the function bar of B is called.
you can wright
D* pD = new D;
pD->bar();
Upvotes: 0
Reputation: 137820
You have used virtual
for foo
but not bar
. This program demonstrates the effect of that keyword: it signals to consider the dynamic or runtime type of the object. Without it, the compiler generates a direct function call using only the static or compile-time type information.
Upvotes: 3