tags:

views:

88

answers:

3
class B{
private:
   void DoSomething();
}

class W{
private: 
   class D: public B{
   }

   D d; 
}

Can I call private member function in base class of D in the scope of class W?

+5  A: 

Nope. You can never call a private member function from anywhere except the class that owns it. If you want derived classes to be able to access it, declare it protected instead.

You can also declare D to be a 'friend' of class B; that would allow D to access B.DoSomething(). However, this approach is usually frowned upon.

Aric TenEyck
If DoSomething() is public. It seems that I cannot call it in the scope of W , right?
Jinx
If you declare it as public you'll be able to access it from instances of B or instances of any class that extends B. But it has to be from an instance of the class:B b = new B(); b.DoSomething(). You can't just access it directly from W.
MadMurf
+1  A: 

The function DoSomething can be accessed outside the class only if it is declared as public or private. Besides as mentioned above by Aric, the inherited class can become a friend to achieve the same.

The alternative approach would be to declare/define the function as virtual and do not define the virtual definition for the sub/inherited class. Doing this, will call the function definition for the base class.

Roopesh Majeti
A small correction in the the first line [ of my answer ], i mentioned it as "declared as public or private". It should be "public or protected"
Roopesh Majeti
@Roopesh you can edit the answer to correct it rather than leaving a comment. Just so you know StackOverflow provides the option.
MadMurf
+1  A: 

No, if you use the protected keyword then you can. The fact that it is a nested class is irrelevant.

hacim