Hello,
I would like to access (use) a (virtual) method declared in a base class via a pointer to an object belonging to a derived class, which overrides the base method. Is it possible? Up to now I have not been successful. I am including a program with a more detailed description.
Regards,
bostjanv
// declare a base class T0 with virtual function P, and a derived
// class T1 which overrides P; declare two ptrs, to T0 and T1,
// and generate corresponding objects; calling P via the two
// ptrs gives expected result; however I would like to take
// ptr to T1 object & execute the base function (declared
// in T0); is it possible? I tried all possible casts but nothing
// works; no matter how I cast the pt1 ptr, I always end up executing
// the overriding function (declared in T1)
//
// actual output (debian 7, gcc 4.7.2-5):
// T0 class
// T1 class
// T1 class
// T1 class
// T1 class
#include <stdlib.h>
#include <iostream>
class T0 {
public:
virtualvoid P() {
std::cout << "T0 class" << std::endl;
}
} *pt0,*ppt0;
class T1: public T0 {
public:
void P() {
std::cout << "T1 class" << std::endl;
}
} *pt1;
int main(int argc, char *argv[]) {
pt0=new T0;
pt1=new T1;
pt0->P(); // output as expected: T0 class
pt0=pt1;
pt0->P(); // output as expected: T1 class
ppt0=dynamic_cast<T0*>(pt1);
ppt0->P(); // I thought I would get the output "T0 class", but actually
// got "T1 class"
ppt0=static_cast<T0*>(pt1);
ppt0->P(); // I thought I would get the output "T0 class", but actually
// got "T1 class"
ppt0=reinterpret_cast<T0*>(pt1);
ppt0->P(); // I thought I would get the output "T0 class", but actually
// got "T1 class"
}
Herb Sutter has a recommendation to make virtual functions private and to call them form non-virtual member of the base. The idea is that the base should define interface and the derived classes merely fine-tune the implementation.
The relevance to the OP question is that one should recheck the design, if the interface provided by the base is not sufficient. Explicit reference to a class in the hierarchy (T0::) adds a dependency.
Thanks for the comment. I think I get the general idea although I would appreciate a longer reference. For the moment the p1->TO::P() solution will do. Regards, bostjanv