pointer vs non-pointer members of a class

前端 未结 5 1079
深忆病人
深忆病人 2021-02-02 02:26

My questions is, suppose we have two classes A and B. I want to have an object of B in class A.

Should I use,

class A
{
  public:
          A();
                 


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 02:58

    It depends.

    Even if you use the pointer, you can initialize the member in the initialization list, but that's not your biggest concern.

    There are advantages and disadvantages to both:

    Using a pointer:

    Pros:

    • the class will be smaller in memory

    • you only need a forward declaration to the other class - no need to include the other header in your header

    • can use derived objects from B as members

    Cons:

    • memory management - this is a pretty big one. Do you want the memory to be managed by the class (override destructor, assignment operator and copy constructor)?

    Using an object:

    Pros:

    • no need to worry about memory management

    Cons:

    • can only use objects of the base class. What if you want to derive from B?

    • more memory for each instance

    • constructor of B will be called on construction of A

    • you need the full definition of B inside the header

    I'll edit my answer if I think of more.

提交回复
热议问题