Search code examples
c++inheritanceclass-template

Which members are inherited from the template parameter


If we have a class template like

template<class Type>
class Field {
....
}; 

Now, if I declared an object of class Field as

Field <vector> velocityField;

So which member functions is inherited form vector to my velocityField


Solution

  • Template parameters allow the compiler to perform a substitution of the generic template parameter itself, when the compiler finds a declaration of a concrete type. You are not inheriting anything.

    If you use Type somewhere in your Field class, the substitution is performed accordingly and only the referenced method are looked up by the compiler.

    template<class Type>
    class Field {
      void Foo()
      {
        Type instanceOfType;
        instanceOfType.clear();
      }
      void NeverCalledMethod()
      {
         Bar(); //bar doesn't exist
      }
    }; 
    
    Field<vector> aField; // here the type Field<vector> is instantiated for the first time.
    aField.Foo(); // only here the template class Foo() method is included by the compiler.
    

    Under certain circumstances(eg. Bar()'s body has a valid syntax), the compilation won't be affected by an error in its body, if Bar() it's never called. Because Bar() it's never called, and the compiler can parse it but won't try to actually compile it, the above code won't produce any compiler error.