Whilst digging through the STL sources (DinkumWare, SGI, STLport, etc..) and trying to make sense of their implementation choices (it’s going well), I came across something I feel is a bit odd or rather ive never run into before.
Generally when one wishes to overload a member function in a derived class, you would prepend the base class member function signature with the virtual keyword, however at various points in the STL source this is not the case.
Here is a cut-down version of what I’m seeing in the STL implementations:
template <typename T> class A {
public:
void func( ) { std::cout << "inside A func( )" << std::endl; }
};
template <typename T> class B : public A<T> {
public:
void func( ) { std::cout << "inside B func( )" << std::endl; }
};
The compiler seems fine with this pseudo-polymorphism, where as I was expecting an error something along the lines of:
error C2535: 'void B<T>::func(void)': member function already defined or declared
Would someone be kind enough to explain what is going on here?
PS: This also seems to work without the classes being templates too.
‘Regards
Without the
virtualkeyword – when redefining a function, you are hiding the super’s function.In your case, by redifining
func(), you tell the compiler there is a new function forB, which is different fromA‘s.Though, because it is not declared
virtual, you will see this affect only if you invokefunc()from a variable of typeB. A variable of typeAwhich holds aB, will invokeA‘s func().will invoke the first [
A‘s] method.To invoke
B‘s method, you need the type to beB: