开发者

Can derived class access private static member function

开发者 https://www.devze.com 2023-02-24 17:27 出处:网络
I have a code like this, it seems it works. I have no idea why private static method can be accessed like this.

I have a code like this, it seems it works. I have no idea why private static method can be accessed like this.

class Base
{
   public:
      static void f(){std::cout<<"in base开发者_开发知识库\n";};
};

class Derived:private Base
{
};


int main()
{

   Derived::f();
   return 0;
}


Refused by all compilers I've tried (several g++ version, como online, IBM xlC) excepted sun CC. My guess is that it is a bug in your compiler.


No, f should not be accessible via Derived (except a member function) as Base is inherited privately. GCC correctly reports this error:

temp.cpp:6: error: ‘static void Base::f()’ is inaccessible
temp.cpp:17: error: within this contex


in your code f() is privately inherited so you can't access it like this

int main()
{

   Derived::f();
   return 0;
}

accessibility error for f()


In Private Inheritance, All the members of the Base Class become Private memebers of the Derived Class

Class Derived derives Privately from Class Base, Hence the member function Base::f() becomes Private member of the Derived class. A Private member of an class cannot be accessed from outside the class(only accessible inside class member functions) Hence the code cannot compile cleanly.

The fact that f() is static function has no effect on these basic rules of inheritance and Access specifiers. A non static member function in Base would show the same behavior.

If your compiler compiles this code then it has a bug which you should report.

0

精彩评论

暂无评论...
验证码 换一张
取 消