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,getNin the base class is declaredprivate.Make
getNpublic as:1. I mean, a class defined with the keyword
class. Note that class can be defined with the keywordstructandunionas well, according to the C++ Standard.EDIT:
If you think because
SubClassis a friend ofBase, so it can access private members ofBasefrom outside, then that is wrong.friendmeans member functions ofSubClasscan access private members ofBaseclass.However, if you make
main()friend ofBase, then your code would work:Now from
main(), any private members ofBasecan be accessed!See this demo : http://www.ideone.com/UKkCF