skydoor
skydoor

Reputation: 25868

Can derived class access private static member function

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;
}

Upvotes: 0

Views: 1144

Answers (4)

Alok Save
Alok Save

Reputation: 206498

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.

Upvotes: 0

Badr
Badr

Reputation: 10648

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

Upvotes: 0

edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31851

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

Upvotes: 1

AProgrammer
AProgrammer

Reputation: 52274

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.

Upvotes: 3

Related Questions