Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static method overrides base class non-static method?

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:

  1. static method doesn't override the virtual functions in base class
  2. Function pointer signature for both the cases are different

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 ?)

like image 413
iammilind Avatar asked Jun 16 '11 06:06

iammilind


People also ask

Why static method is overridden?

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.

Why would override a method of a base class?

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).

Can non static method override static method?

A static method cannot override non static method. A non static method cannot override static method.

Can non static method be override?

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.


2 Answers

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.

like image 135
CB Bailey Avatar answered Sep 24 '22 06:09

CB Bailey


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).

like image 31
Šimon Tóth Avatar answered Sep 24 '22 06:09

Šimon Tóth