This forum has been archived. All content is frozen. Please use KDE Discuss instead.

How do I keep track of the calling parent class?

Tags: None
(comma "," separated)
User avatar
lin-unix
Registered Member
Posts
34
Karma
0
OS
In an initialization method in a newly instantiated class, I would like to run some code based on which parent instantiated this class.

For example:
Code: Select all
ButtonBox::ButtonBox(QWidget *parent)
{
    if(parent == something) {
        //then do something
    }
    else if(some other parent) {
        //then do something else
    }

    //Now do all the common tasks
}


How would I be able to figure out which parent instantiated the class, so that the proper code is run?
User avatar
bcooksley
Administrator
Posts
19765
Karma
87
OS
Assuming those classes are based on QObject or QWidget, then you can rely on the presence of QMetaObject, and can extract the class name through that. I question why you wish to make your code deterministic on it's parent's class however.


KDE Sysadmin
[img]content/bcooksley_sig.png[/img]
User avatar
lin-unix
Registered Member
Posts
34
Karma
0
OS
I'm setting up a generic buttonbox and which buttons are created are based on the parent class that wants the buttonbox. There is a lot of common code so I think it is more efficient not to have multiple button box classes that are almost identical :)

Essentially just an if block here and there to create specific buttons based on the window that is being created.
Musikolo
Registered Member
Posts
27
Karma
0
OS
@lin-unix: Have you considered the possibility of using some sort of virtual (abstract) class implementing all the common code and rely the variable one to other virtual methods? In some point of you common code, you can invoke the virtual (unimplemented) methods that must be coded by other children classes. Of course, you also need implement as many children classes as different behaviours you wish/need to have?

Although not sure, maybe it could also be useful to apply the Strategy Design Pattern: http://en.wikipedia.org/wiki/Strategy_pattern This pattern allows you to have different classes sharing all the same parent class or interface. The complexity of what particular actions are carried out is left to each concrete implementation, rather that on the caller context. A typical example it to have a Shape parent class having a getArea() method. Depending whether your Shape is a Circle or a Square, you getArea() method would have a different implementation. The big advantage of this approach is that the invoker does not care what the concrete Shape is using as for all of them the getArea() method is properly coded.

I hope it helps! ;)


Bookmarks



Who is online

Registered users: Bing [Bot], Evergrowing, Google [Bot], rockscient