Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Parent methods and accessing private variable in a Parent class?

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;
}
like image 940
mike_b Avatar asked Oct 24 '10 17:10

mike_b


1 Answers

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.

like image 91
Ned Batchelder Avatar answered Nov 08 '22 11:11

Ned Batchelder