dynamic binding issue

  • Thread starter Christof Warlich
  • Start date
C

Christof Warlich

Hi,

obviously, I'm missing something w.r.t. dynamic binding in C++:

Can anyone explain why the code below prints "Base" instead of
"Derived" when calling the Base constructor? I'm calling f() on
a Derived instance in the Base constructor, right? So why isn't
the f() of Derived called as it is in main()?

Can I work around this to get the behaviour that I expected?

Thanks,

Christof

#include <iostream>
#include <typeinfo>
class Base {
public:
Base(Base *x) {
x->f(); // why base??
}
virtual void f(void) {
std::cout << "Base\n";
}
};
class Derived:public Base {
public:
Derived():
Base(this) {
}
void f(void) {
std::cout << "Derived\n";
}
};
int main(void) {
Derived derived;
Base &base = derived;
base.f(); // ok, derived
}
 
R

red floyd

Christof said:
Hi,

obviously, I'm missing something w.r.t. dynamic binding in C++:

Can anyone explain why the code below prints "Base" instead of
"Derived" when calling the Base constructor? I'm calling f() on
a Derived instance in the Base constructor, right? So why isn't
the f() of Derived called as it is in main()?

Can I work around this to get the behaviour that I expected?

Thanks,

This is FAQ 23.5
http://parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.5

Essentially, the reason is that the Derived portion hasn't been
constructed yet.
 
J

Jerry Coffin

Hi,

obviously, I'm missing something w.r.t. dynamic binding in C++:

Can anyone explain why the code below prints "Base" instead of
"Derived" when calling the Base constructor? I'm calling f() on
a Derived instance in the Base constructor, right? So why isn't
the f() of Derived called as it is in main()?

Can I work around this to get the behaviour that I expected?

While a constructor is running, the type (the ONLY) type of that object
is the type of the class of that constructor. IOW, while the base class
ctor is running, the the type of the object is the base class, so when
you call a virtual function, that's the class' virtual function that
will be called.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top