PDA

View Full Version : How to call a function in the mother object from a child object?



Momergil
14th December 2011, 15:44
Hello!

Offently we create classes and instantiate objects from thoose classes in other objects of other classes (so in a Mother Object, a QMainWindow, I insert a Child Object, such as a QPushButton). Normally what is done is that in the Mother Object we work with the Child Object, using its functions. So for example:


void MainWindow::useChildObject()
{
QPushButton pb;
pb.setChecked(true);
}

But how should I proceed if I want to use a function of the MOther Object from the Child Object? In other words, I'm there editting the .cpp of a QPushButton and in a moment I want to call a function of MainWindow from it. How should I do this?

For now I'm using the SIgnals and Slots mechanism, and this have being fine till I find that there are some times when I need to get the result of a Main Object function (a return value), what can't be done by the Signals and Slots mechanism (as far as I know).

So, how do I call a function of a Mother Object and even use its returns from a Child Object?


Thanks!


Momergil

stampede
14th December 2011, 16:41
I'm there editting the .cpp of a QPushButton
Don't do that, I'm 1000% sure its not needed. If you need a computation result in a button class, then it means that something is wrong with your design - a button is just a gui control, its only to process the user input, should be independent of the program logic.
Post more details about your problem, I'm sure we can help you redesign the implementation.

Momergil
15th December 2011, 16:45
Don't do that, I'm 1000% sure its not needed. If you need a computation result in a button class, then it means that something is wrong with your design - a button is just a gui control, its only to process the user input, should be independent of the program logic.
Post more details about your problem, I'm sure we can help you redesign the implementation.

Nonono! you misunderstood my point! xD

The QPushButton was only an example!! It could be any object-class, lets suppose, one that I created. So don't concentrate in that being a QPushButton, but in being a class!!


Momergil

nish
15th December 2011, 20:42
Add a pointer of your parent class in your child class, change the constructors to pass the parent pointer. Once you have the parent pointer inside child you can easily access any public method of parent.

amleto
18th December 2011, 15:49
You can do this, but it makes the parent-child system highly coupled. This is not a good situation to be in as the design is not flexible, and is not modular. Now you cannot use your child component anywhere - it must be used with only specific parents.

When this happens you should be looking at doing some dependency inversion (http://en.wikipedia.org/wiki/Dependency_inversion_principle)