how to access base method via derived pointer

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 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:
  virtual void 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"
}
Last edited on
Please use code tags when posting code, to make it readable.
You can use the scope resolution operator.
Thanks, kulkarnisr. I tried p1->T0::P(), and it worked. Regards, bostjanv
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
Topic archived. No new replies allowed.