-
September 9th, 2009, 11:11 PM
#1
Confusion of friend with private inheritance
Code:
class Base{
int a;
public:
int b;
Base(){a = 10; b = 11;}
virtual ~Base(){};
class Derived;
friend Derived;
};
class Derived: private Base{
public:
Derived(){cout<<b<<endl;}
void p(Base b){cout<<b.a<<endl;};
virtual ~Derived(){};
};
int main(){
Base b;
Derived d;
d.p(b);
return 0;
}
I tried this code, and it can not compile in VC++. As my understanding, Derived is defined as Base's friend, so it can access Base's private member. Can anyone explain it? Thanks
Last edited by CJIAJIA; September 14th, 2009 at 05:01 AM.
-
September 10th, 2009, 01:07 AM
#2
Re: Confusion of friend with private inheritance
Move
class Derived;
to before the Base class declaration.
-
September 10th, 2009, 01:58 AM
#3
Re: Confusion of friend with private inheritance
Thanks a lot!. but what is the difference between putting the forward declaration inside and outside of the class?
-
September 10th, 2009, 03:41 AM
#4
Re: Confusion of friend with private inheritance
Originally Posted by CJIAJIA
Thanks a lot!. but what is the difference between putting the forward declaration inside and outside of the class?
Well it works if you do.
Just kidding. C++ allows you to declare so called inner classes and if you put a forward declaration within a class definition it's considered an inner class.
If you keep the forward declaration of Derived inside of Base and instead change Derived to,
Code:
class Base::Derived: private Base {
it should work too with the difference that Derived is now an inner class of Base.
Last edited by nuzzle; September 10th, 2009 at 03:46 AM.
-
September 10th, 2009, 03:47 AM
#5
Re: Confusion of friend with private inheritance
you rock! Many thanks to your insightful explanation!
-
September 10th, 2009, 03:51 AM
#6
Re: Confusion of friend with private inheritance
Originally Posted by CJIAJIA
I tried this code, and it can not compile in VC++. As my understanding, Derived is defined as Base's friend, so it can access Base's private member. Can anyone explain it? Thanks
This is a very strange way to achieve this.
If you have members in your base class that you need to access from Derived, declare them as protected.
Regards,
Zachm
-
September 10th, 2009, 03:58 AM
#7
Re: Confusion of friend with private inheritance
Originally Posted by CJIAJIA
you rock! Many thanks to your insightful explanation!
You're wellcome.
I've assumed that you're just testing things out so I've not commented on your code but as Zachm notes it's quite "unorthodox" in its present form.
-
September 13th, 2009, 11:42 PM
#8
Re: Confusion of friend with private inheritance
Yes, Zachm and nuzzle, I am trying to using some tricky way to help me dig inside C++. It is not in the real programming.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|