Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ OOP quiz question

Tags:

c++

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
like image 732
Adrian Avatar asked May 12 '11 11:05

Adrian


1 Answers

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

like image 76
Nawaz Avatar answered Oct 12 '22 07:10

Nawaz