Interview Question
code will not compile,
though we are creating base class object (Base b) inside derived class, we cant access the private member 'a' of the base class inside the derived class.
'b.a' inside the derived class is the problem in code. 'a' is private member of base class.
But the dervied class is friend of base class and friend can access private members. It got compiled.
But the "Derived" inside of "Base" is different from "Derived" out side of "Base". The former's full scope is Base::Derived and the latter's full schope is ::Derived
::Derived is not a friend of Base.
the code will not and should not compile due to:
1. a being private and being accessed by privately derived b
2. friend declaration should error as class key is not there
In C++ u don't have to explicitly specify class or struct keyword unlike C ... It wont give error because of u havent written "class" keyword. It would give error saying that it cannot access the private members of Base.
I guess the reason is different. Not sure exactly what does 'friend Derived' means rather that 'friend class Derived'. Yes the friend class Derived would definitely solve the problem. But your explanation is wrong .
It can be compiled after the following changes (I tried it):
1. change "class Derived; friend Derived;" to "friend class Derived;"
2. move "friend class Derived;" to the first line of class Base
Here class derived is declared within base which means derived is a nested class within base.
The class defined outside is a different class with the same name(of course to confuse). I hope the code given below will help you
class Base{
int a;
public:
int b;
Base(){a = 10; b = 11;}
virtual ~Base(){};
class Derived;
friend Derived;
};
class Base::Derived{
public:
//Derived(){cout<<b<<endl;}
void p(Base b){cout<<b.a<<endl;};
virtual ~Derived(){};
};
int main(){
Base b;
Base::Derived d;
d.p(b);
return 0;
}
As per the standards, there should be a elaborated type (containing class or struct keywords)in the friend declaration.
That's why "friend Derived" will not work.
The solution given by Ashish is incorrect (please try it on g++). Also you changed the inheritance to containment which will change the original problem definition.
change "class Derived; friend Derived;" to "friend class Derived;". will compile
- Jofen October 08, 2009