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?
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.
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.
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.
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.
Do this:
struct Derived2: public Derived1 { void SomeInstanceMethod(){ ::Base::SomeStaticMethod(); // ^^ // Notice leading :: for accessing root namespace. } };
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.
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