Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a static method from a private base class?

Tags:

Due to the layout of a third-party library, I have something like the following code:

struct Base {     static void SomeStaticMethod(){} };  struct Derived1: private Base {};  struct Derived2: public Derived1 {     void SomeInstanceMethod(){         Base::SomeStaticMethod();     } };  int main() {     Derived2 d2;     d2.SomeInstanceMethod();      return 0; } 

I'm getting compiler error C2247 with MSVC:

Base::SomeStaticMethod not accessible because Derived1 uses private to inherit from Base.

I know I can't access Base members from Derived2 via inheritance because of the private specifier, but I should still be able to call a static method of Base - regardless of any inheritance relationship between Base and Derived2.
How do I resolve the ambiguity and tell the compiler I'm just making a call to a static method?

like image 505
Carlton Avatar asked Sep 06 '16 13:09

Carlton


People also ask

How do you call a static method in base class?

A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.

Can static methods access private methods?

Yes, we can have private methods or private static methods in an interface in Java 9. We can use these methods to remove the code redundancy. Private methods can be useful or accessible only within that interface only. We can't access or inherit private methods from one interface to another interface or class.

How do you call a static member of a class?

Because static member functions are not attached to a particular object, they can be called directly by using the class name and the scope resolution operator.

Can I call a static method inside a regular method?

A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.


2 Answers

Do this:

struct Derived2: public Derived1 {     void SomeInstanceMethod(){         ::Base::SomeStaticMethod(); //      ^^ //      Notice leading :: for accessing root namespace.     } }; 
like image 109
michalsrb Avatar answered Sep 21 '22 06:09

michalsrb


I think michalsrb's answer is better, but for completeness:

namespace {     void SomeStaticMethodProxy()     {         return Base::SomeStaticMethod();     } }  struct Derived2: public Derived1 {     void SomeInstanceMethod(){         SomeStaticMethodProxy();     } }; 

will also work.

like image 20
Martin Bonner supports Monica Avatar answered Sep 20 '22 06:09

Martin Bonner supports Monica