Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

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

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...