struct B {
void foo () {}
};
struct D : B {
using B::foo;
static void foo () {}
};
int main ()
{
D obj;
obj.foo(); // calls D::foo() !?
}
Member method and static
member method are entirely different for 2 reasons:
static
method doesn't override the
virtual functions in base class
When a method is called by an object, shouldn't the member method have higher preference logically ? (Just that C++ allows static
method to be called using object, would it be considered as an overridden method ?)
No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods. The calling of method depends upon the type of object that calls the static method.
Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. It allows for a specific type of polymorphism (subtyping).
A static method cannot override non static method. A non static method cannot override static method.
Non-static method uses run time binding or dynamic binding. A static method cannot be overridden being compile time binding. A non-static method can be overridden being dynamic binding.
The rule that you are seeing is described in ISO/IEC 14882:2003 7.3.3 [namespace.udecl] / 12 :
When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions with the same name and parameter types in a base class (rather than conflicting).
Without this rule, the function call would be ambiguous.
The issue here is that you can't overload a static method using a non-static method with the same signature.
Now, if you try:
struct D {
void foo () {}
static void foo () {}
};
It will trigger an error.
I'm not really sure why in case of using B::foo
it is actually silently ignored without triggering an error/warning (at least on GCC 4.5.1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With