3

Possible Duplicate:
C++ equivalent of “super”?

Is it possible to call a base class member function in a sub class, without knowing name of base class? (something like use super keyword in java)

Community
  • 1
  • 1
Ehsan Khodarahmi
  • 4,772
  • 10
  • 60
  • 87
  • 3
    How would you not know the name of the base class? – templatetypedef Jul 11 '12 at 04:23
  • No, C++ doesn't have an equivalent of `super`. Since it supports multiple inheritance, a `super` could refer to several different classes, not just one like in Java. – Jerry Coffin Jul 11 '12 at 04:28
  • 2
    Since you must name the base class to define the derived class, you must know the name (or, at least, _a_ name) for the base class. Then, there's nothing stopping you from `typedef base_class_name super;`. – James McNellis Jul 11 '12 at 04:32
  • @JamesMcNellis: Nothing except decency, good taste, common sense, etc. – Jerry Coffin Jul 11 '12 at 04:33
  • 2
    @JerryCoffin: Sometimes this is a useful technique. Consider a base class with a very, very long name, e.g. `std::conditional::type`, where `B1` and `B2` are long type names, the expression may be complex, and everything might be dependent. I can recall having done this a few times, though I usually name the typedef `base_type` or something similar, rather than `super` (since I've never used this "Java" thing). – James McNellis Jul 11 '12 at 05:11

1 Answers1

1

C++ doesn't have a standard equivalent for super keyword. But there is a microsoft specific one __super which I think achieves the same thing if you are using visual studio.

// deriv_super.cpp
// compile with: /c
struct B1 {
   void mf(int) {}
};

struct B2 {
   void mf(short) {}

   void mf(char) {}
};

struct D : B1, B2 {
   void mf(short) {
      __super::mf(1);   // Calls B1::mf(int)
      __super::mf('s');   // Calls B2::mf(char)
   }
};

Refer: msdn

Ragesh Chakkadath
  • 1,521
  • 1
  • 14
  • 32
  • Wouldn't that do the same without the `__super::`? – steffen Jul 11 '12 at 05:30
  • @steffen It does work if there is only single inheritance and a different function name for `struct D`. In current case, first call of `mf` itself cause infinite recursion as the calling function also matches the same. if the `struct D`'s function name is not `mf`, it will generate a compiler error: `reference to 'mf' is ambiguous`. – Ragesh Chakkadath Jul 11 '12 at 05:49