Alex Rivera | Logout

Is it bad practice for a child object to have a pointer to its parent?

Asked 2010-09-16T06:00:13.240
16

In a C++ application, let's say I have a window class, which has several instances of a control class. If my window wanted to notify a control that it had been clicked, I might use:

control[n]->onClick();

Now let's say that the control needs to know the size of it's parent window, or some other information. For this I was considering giving the control a pointer to itself (this) as a parameter to it's constructor. I would then make a call like this from the controls onClick() method:

Size windowsize = parent->getSize();

Would this be considered bad practice, or in any other way contradict the values of object orientated programming? If so, what would he the 'proper' way of doing this?

As a side question, would it be better to have a vector of Class or Class*? Is it worth the added complexity for the speed gain? (Changes to the vector would be infrequent).

Edit
Report

2 Answers

13

You can consider a hierarchy of controls as being a tree-like graph data structure; when you visualize it that way, it's quite reasonable for a control to have a pointer to its parent.

As for whether objects or pointers to objects should be stored in a vector, well, it depends. You should usually prefer to store objects, but there are a lot of times that you can't do so or it's impractical to do so. For example, if you need to take advantage of polymorphism and store different types of things all derived from a common base class, you'll need to use pointers.

If you do store pointers, make sure to either use a smart pointer of some kind or a pointer container; otherwise, exception safety is a beating.

answered 2010-09-16T06:13:43.207
5

No, it's completely fine. The only issue is that it increases the level of coupling between instances. Also, if you consider usage of smart pointers as advised above, be sure that you make the reference to parent 'weak'. Assuming your window trees are not too deep, you could consider to determine the parent dyuamica1ly, starting from a known top window.

answered 2010-09-16T07:10:30.513

Your Answer