Software & Finance





C++ - Difference Between Pointers and References





Pointers can be NULL whereas reference can not.

References must be initalized unlike pointers.

Reference variable in a class must be initialized via C++ initializer list in the constructor.

If we need a optional argument in function, we can use pointer otherwise reference.

 

class MyRefClass

{

private:

    int &a;

    int &b;

    MyRefClass();

public:

    // Ignoring the initialization will give an compile time error error C2758: 'MyRefClass::b' : must be initialized in constructor base/member initializer list

    MyRefClass(int arg1, int arg2) : a(arg1), b(arg2)

    {

    }

};