I'm doing a C++ quiz and I need to say whats wrong in the following code:
class Base {
friend class SubClass;
int n;
virtual int getN()
{
return n;
}
};
class SubClass: public Base {
public:
SubClass() {}
SubClass(const SubClass& s) {}
};
int main()
{
SubClass sc;
if(sc.getN() <= 5)
{
int x = sc.getN();
}
return 0;
}
Besides that n is uninitilized and maybe the object should be created through a Base class pointer, what else could be wrong?
When I run it I get this error:
error: 'virtual int Base::getN()' is private
As by default every member of a class1 is private
, getN
in the base class is declared private
.
Make getN
public as:
class Base {
friend class SubClass;
int n;
public: //<--------------------- you forgot this
virtual int getN()
{
return n;
}
};
1. I mean, a class defined with the keyword class
. Note that class can be defined with the keyword struct
and union
as well, according to the C++ Standard.
EDIT:
If you think because SubClass
is a friend of Base
, so it can access private members of Base
from outside, then that is wrong. friend
means member functions of SubClass
can access private members of Base
class.
However, if you make main()
friend of Base
, then your code would work:
class Base {
friend int main(); //make main() friend of Base
//...
};
Now from main()
, any private members of Base
can be accessed!
See this demo : http://www.ideone.com/UKkCF
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With