Search code examples
c++language-design

Rationale behind C++ member variables declaration


I am still pretty new to c++ and would like to understand the thought process behind creating member variables the way it is. For example, if I go through a header file, I see some of the member variables are declared as pointers while some others are declared as references.

// in foo.h

class Foo {
  private:
    A* const a;
    B& b;
    std::unique_ptr<C> c;
};

What is the difference between declaring (is this even the correct terminology?) a,b & c the way it is? I understand that a is const pointer, i.e., it points to some memory holding an object of type A & b is a reference. c is a unique_ptr holding an object of type C. But I don't understand why you would want to declare something this way. I come from a Java/Python background so please bear with my confusion.


Solution

  • B& b;
    

    The above is a reference to a B object. As a reference, it can never be NULL, and it cannot be re-targeted to refer to a different object than the one it was originally initialized to refer to. You can also access it via the same syntax that you would use for a "normal" member-variable (e.g. as if it were B b;). Since it is unchangeable, its presence means that you must set it as via an initializer in each of your constructors, otherwise you will get a compile-time error.

    A* const a;
    

    The above is a pointer to a read-only A object... or it could be set to NULL, in which case it isn't pointing to anything valid at all. Since its value can be changed at run-time, it does not need to be initialized by your object's constructors (although it is considered good practice to at least initialize it to NULL, so that if any of your code tries to access it before it is set, you'll be more likely to get an obvious/reproducible crash)

    std::unique_ptr<C> c;
    

    This is similar to C * c; except better (assuming your object is intended to "own" the C object), because it explicitly indicates the ownership relation and will automatically delete the pointed-to C object when the unique_ptr is deleted.