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 Derivedublic Base {
public:
Derived():
Base(this) {
}
void f(void) {
std::cout << "Derived\n";
}
};
int main(void) {
Derived derived;
Base &base = derived;
base.f(); // ok, derived
}
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 Derivedublic Base {
public:
Derived():
Base(this) {
}
void f(void) {
std::cout << "Derived\n";
}
};
int main(void) {
Derived derived;
Base &base = derived;
base.f(); // ok, derived
}