CornSmith
CornSmith

Reputation: 2037

Using protected data in a parent, passed into a child class

How can I access the data in a parent's class, which is protected, when passed into a derived class.

class parent
{ 
    protected:
        int a;
};

class child : public parent
{
    void addOne(parent * &);
};

void child::addOne(parent * & parentClass)
{
    parentClass->a += 1;
}

int main()
{
    parent a;
    child b;

    parent* ap = &a;

    b.addOne(ap);
}

Upvotes: 1

Views: 210

Answers (1)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234584

You cannot access protected data via a pointer/reference to the base class. This is to prevent you from breaking the invariants that other derived classes may have on that data.

class parent
{
    void f();
    // let's pretend parent has these invariants:
    // after f(), a shall be 0
    // a shall never be < 0.

    protected:
        int a;
};

class child : public parent
{
public:
    void addOne(parent * &);
};


class stronger_child : public parent
{
public:
    stronger_child(int new_a) {
        if(new_a > 2) a = 0;
        else a = new_a;
    }
    // this class holds a stronger invariant on a: it's not greater than 2!
    // possible functions that depend on this invariant not depicted :)
};

void child::addOne(parent * & parentClass)
{
    // parentClass could be another sibling!
    parentClass->a += 1;
}

int main()
{
    stronger_child a(2);
    child b;

    parent* ap = &a;

    b.addOne(ap); // oops! breaks stronger_child's invariants!
}

Upvotes: 2

Related Questions