Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decide whether class attributes should be pointer or value while using composition in C++?

See this example.

an University class has a Director and many student So my class will be like this

a)

class University {
    Director d;
    Student list[1000];
};

or

b)

class University {
    Director* d;
    Student* list[1000];
};

My problem is how to decide whether class attributes should be pointer or value.

like image 809
user966379 Avatar asked Oct 26 '25 18:10

user966379


1 Answers

Most all other answers focus on the detail of heap vs. direct containment (or provide no information at all, like use pointers when you want pointers... Rather than focusing on the details, consider the overall design of the application.

The first question would be about ownership. In your program, are those students and director owned by the class? Or do they exist outside of the class scope. In most simple applications, the objects might only exist inside the class, but in other more complex designs, the students might belong to the school, and only be referenced in the class (or the director might also teach some courses to other classes). If the class owns the objects, the composition will be the best approach: hold the director directly as a member, and the students inside a container that is directly held by the class (I would recommend a vector, which is the safe choice for most cases).

If the objects don't belong to the class, then you will rather use aggregation. Whoever owns the object will have to manage the lifetimes and decide how to store the real objects and the class would only hold references (in the general sense) to those objects. Things get more complicated as there are more choices. If ownership can be transferred, then you would dynamically allocate the objects and hold pointers, where you should read smart pointers so that memory will be managed for you.

If ownership does not change and the lifetime of the students/director are guaranteed to extend beyond the lifetime of the class, you could use references. In particular for the director. In the case of the students, it will be more complex as you cannot have containers of plain references, so the solution might still be pointers there, a vector of pointers. Another issue with references is that they cannot be reseated, which means that if you hold a reference to the director, the director of the class will be fixed for the whole lifetime of the class and you won't be able to replace her.

Design is somehow complicated and you will learn with experience, but hopefully this will provide a quick start onto your problem.

like image 88
David Rodríguez - dribeas Avatar answered Oct 29 '25 07:10

David Rodríguez - dribeas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!