C++ – when should I use a pointer member in a class

A pointer has following advantages:

a) You can do a lazy initialization, that means to init / create the object only short before the first real usage.

b) The design: if you use pointers for members of an external class type, you can place a forward declaration above your class and thus don’t need to include the headers of that types in your header – instead of that you include the third party headers in your .cpp – that has the advantage to reduce the compile time and prevents side effects by including too many other headers.

class ExtCamera;  // forward declaration to external class type in "ExtCamera.h"

class MyCamera {
public: 
  MyCamera() : m_pCamera(0) { }

  void init(const ExtCamera &cam);

private:
   ExtCamera  *m_pCamera;   // do not use it in inline code inside header!
};

c) A pointer can be deleted anytime – so you have more control about the livetime and can re-create an object – for example in case of a failure.

Leave a Comment

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