I have a base class Base
and a number of sub classes BaseDerivate1
.. BaseDerivateN
. Part of my code is generic and supports any of the sub classes by accessing the used class via a define BASE_DERIVATE
.
I now need to add a static function that the child classes can declare but don't have to. For derived classes that declare StaticFunc()
, I want to call it. In all other cases, I want to call the fallback function Base::StaticFunc()
. The call looks like this:
#define BASE_DERIVATE BaseDerivate1 // or some other child class
// somewhere else:
BASE_DERIVATE::StaticFunc();
So I intentionally use name hiding here. The StaticFunc
is never called from within the class. The question I have is: Is this supported by the C++ standard or would this lead to compiler errors for some compilers. Also: Is there a better way to do "static inheritance"? I am stuck with the define BASE_DERIVATE
concept however.
This will "just work":
#include <iostream>
class Base {
public: static void foo() { std::cout << "Base::foo()\n"; }
};
class Derived1 : public Base { };
class Derived2 : public Base {
public: static void foo() { std::cout << "Derived2::foo()\n"; }
};
int main() {
Derived1::foo(); // prints "Base::foo()"
Derived2::foo(); // prints "Derived2::foo()"
}
It's the use of regular name shadowing, which works just the same for static members. The Base
static implemenation is still available from Derived2
by means of rather funny syntax:
Derived2::Base::foo();