Pretty basic question. Has to do with design preference but I think there are some caveats that I'm missing.
I want to have an instance of some class inside another class. The way I see it, I have 3 options:
-
Have the object
class2
insideclass1
as I have it below. This means it gets constructed when an instance ofclass1
gets constructed. My issue here is that it may need a default and/or copy constructor? When I instantiate aclass1
object below, does it constructclass2_inst(args)
using that constructor? Or isclass2_inst
already created with some default constructor and the lineclass2_inst(args)
simply copies an anonymousclass2
object?class class2 { public class2(args) { ... } } class class1 { protected class2 class2_inst; public class1(args) : class2_inst(args) { ... } }
-
I can have a pointer to
class2
:class class2 { public class2(args) { ... } } class class1 { protected class2* class2_inst; public class1(args) { class2_inst = new class2(args); ... } }
This has the advantage that class2 isn't instantiated until I explicitly call the new operator.
-
Then there's using a reference instead of a pointer:
class class2 { public class2(args) { ... } } class class1 { protected class2& class2_inst; public class1(args) { class2_inst = new class2(args); ... } }
I want class2_inst
's life-time to match that of class1
. No funny business with having class2_inst
living outside of class1
. So references may be the way to go.
Of the 3 methods, which is everyone's preferred way, and why?
Aucun commentaire:
Enregistrer un commentaire