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

后端 未结 11 1927
挽巷
挽巷 2020-12-07 12:59

If I create a class MyClass and it has some private member say MyOtherClass, is it better to make MyOtherClass a pointer or not? What does it mean also to have it as not a

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 13:20

    It depends... :-)

    If you use pointers to say a class A, you have to create the object of type A e.g. in the constructor of your class

     m_pA = new A();
    

    Moreover, don't forget to destroy the object in the destructor or you have a memory leak:

    delete m_pA; 
    m_pA = NULL;
    

    Instead, having an object of type A aggregated in your class is easier, you can't forget to destroy it, because this is done automatically at the end of lifetime of your object.

    On the other hand, having a pointer has the following advantages:

    • If your object is allocated on the stack and type A uses a lot of memory this won't be allocated from the stack but from the heap.

    • You can construct your A object later (e.g. in a method Create) or destroy it earlier (in method Close)

提交回复
热议问题