简体   繁体   中英

Accessing parent class variables

I feel like this should be easy but I still can't get the darn thing to work properly.

I don't know what is best practice here. I first started out by trying to store the variable passed to the child class as by reference and then calling on it within the child class. Except, when the variable changes inside the parent class, the child is not seeing the change.

The child:

class Child
{
public:
    Child(bool &EndLoop);
    ~Child();

private:
    bool EndLoopRef;
};

Child::Child (bool &EndLoop) : EndLoopRef(EndLoop)
{
}

Child::PrimaryFunction()
{
    while (!Child::EndLoopRef)
    {
        // Main app function is in here
    }

    // EndLoop is true, we can now leave this method
}

The parent:

class Parent
{
public:
    Parent();
    ~Parent();

private:
   bool EndLoop;
};

Parent::Parent()
{
    Child childclass(EndLoop);
    childclass.PrimaryFunction();

    // EndLoop was changed and the loop is now overe
}

To summarize this, parent class passes EndLoop by reference. The child class stores this reference and waits for a true value of EndLoopRef to exit the loop. Needless to say, it's not ending the loop.

FYI, the EndLoop value is changed by a system call in the parent class.

Naming your class member bool EndLoopRef; does not make it a reference. This is still just a bool value, and the constructor's member initialisation will load EndLoop 's value at construction time.

You've already shown you know how to use & to define a reference.

You have not defined it aa reference. You have to say:

bool &EndLoopRef;

A private variable should not be passed by reference. The best way to interact with a private is to have a get() and set() method in the class which has the member variable. In this case your parent value could provide a getEndLoop() function that would return the boolean value.

    Child::PrimaryFunction()
{
    while (!Parent.getEndLoop())
    {
        // Main app function is in here
    }

    // EndLoop is true, we can now leave this method
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM