3

I am reading from ebook Templates complete guide and question which i'm gonna ask might be stupid to you but..

There is section in that 9.4.2 Dependent Base Classes which i am unable to understand.

Here is the partial text from it: http://tinypaste.com/633f0

// Variation 2: 
template<typename T> 
class DD2 : public Base<T> { 
  public: 
    void f() { Base<T>::basefield = 0; } 
}; 

I need help visualizing the line (or problem domain) in text above "Care must be taken with this solution, because if the unqualified nondependent name is used to form a virtual function call, then the qualification inhibits the virtual call mechanism and the meaning of the program changes. Nonetheless, there are situations when the first variation cannot be used and this alternative is appropriate"

I understand unqualified nondependent name etc but mixing them with virtual function call is what eluding me.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Mr.Anubis
  • 5,132
  • 6
  • 29
  • 44
  • 4
    This is a horrible sentance isn't it, this code appears to be designed to allow non-virtual polymorphic behavior. I.e. your derived class can override methods in your base class but the lookup is done at compile time. I suspect "Inhibiting" in this sense means that you're not going to get the usual vtable based dynamic runtime lookup.... – Benj Oct 20 '11 at 12:23
  • Need more context. What is the problem this code is trying to solve? – Raymond Chen Oct 20 '11 at 12:39

2 Answers2

2

If the qualified name ( basefield ) is a virtual function, then the qualification inhibits the virtual call. It's very much the same as if you have:

struct Base {
  virtual void vCall() { }
};

struct Derived : public Base {
  virtual void vCall() { }
};

int main() {
  Derived d;
  Base* inst = &d;
  inst->Base::vCall(); // By qualifying we won't get virtual dispatch;
                       // this calls Base::vCall directly
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Ylisar
  • 4,293
  • 21
  • 27
1

Using a qualified-identifier class-name::function() inhibits virtual-ness of function, so you should use this->function() instead.

This also works for data members: this->basefield.

curiousguy
  • 8,038
  • 2
  • 40
  • 58