views:

49

answers:

4

I'm trying to get the following code to work, but I can't find good-enough documentation on how C++ handles public vs. private inheritance to allow me to do what I want. If someone could explain why I can't access Parent::setSize(int) or Parent::size using private inheritance or Parent::size using public inheritance. To solve this, to I need a getSize() and setSize() method in Parent?

class Parent {
    private:
        int size;

    public:
        void setSize(int s);
};

void Parent::setSize(int s) {
    size = s;
}

class Child : private Parent {
    private:
        int c;

    public:
        void print();
};

void Child::print() {
    cout << size << endl;
}

int main() {
    Child child;

    child.setSize(4);

    child.print();

    return 0;
}
+4  A: 

When you use private inheritance, all public and protected members of the base class become private in the derived class. In your example, setSize becomes private in Child, so you can't call it from main.

Also, size is already private in Parent. Once declared private, a member always remains private to the base class regardless of the type of inheritance.

casablanca
yep, and private members are not inherited, that's why you can't access private members of the base class
Kiril Kirov
You've described what's wrong, but offered no solutions!
Ned Batchelder
@Ned Batchelder: That's why I voted for your answer. :) I'm not sure what exactly the OP wants, because otherwise normal public inheritance would have worked fine.
casablanca
A: 

You cannot access private data-members of other classes. If you want to access private attributes of a superclas, you should do so via public or a protected accessors. As for the rest, see @casablanca's answer.

Space_C0wb0y
+2  A: 

Change Parent to:

protected: int size;

If you want to access the size member from a derived class, but not from outside the class, then you want protected.

Change Child to:

class Child: public Parent

When you say class Child: private Parent, you are saying it should be a secret that Child is a Parent. Your main code makes it clear that you want Child to be manipulated as a Parent, so it should be public inheritance.

Ned Batchelder
A: 

Here's a good link which talks about friend and inheritance levels in C++. Basically:

Access                public    protected   private
members of the same class   yes    yes          yes
members of derived classes   yes    yes          no
not members               yes    no           no
wheaties