Class members that are objects – Pointers or not? C++

If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not?

you should generally declare it as a value in your class. it will be local, there will be less chance for errors, fewer allocations — ultimately fewer things that could go wrong, and the compiler can always know it is there at a specified offset so… it helps optimization and binary reduction at a few levels. there will be a few cases where you know you’ll have to deal with pointer (i.e. polymorphic, shared, requires reallocation), it is typically best to use a pointer only when necessary – especially when it is private/encapsulated.

What does it mean also to have it as not a pointer in terms of where it is stored in memory?

its address will be close to (or equal to) this — gcc (for example) has some advanced options to dump class data (sizes, vtables, offsets)

Will the object be created when the class is created?

yes – the size of MyClass will grow by sizeof(MyOtherClass), or more if the compiler realigns it (e.g. to its natural alignment)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)