Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
If we are from C background, then we sometimes tend to use pointers and not references. It is harmful, because in C++ there are classes, objects, constructors (esp. default and copy constructors), overloaded assignment operator and they come into picture when we pass arguments to functions and assign one object to another.
Let's discuss few areas you may want to keep in mind:
1. References are always initialized and cannot be null; pointers may be nullI cannot define a reference without telling what it refers to. For example the below definition is an error
int & x = NULL; // ERROR
int * ptr = NULL; // OK
So, if I am receiving a reference in a function I don't need to check it against NULL and can safely assume, that it must be getting some lvalue (else it will be compile time error). In case of pointers I cannot assume that, and hence have to put a check like this:
void myFun(int * ptr)
{
if(ptr == NULL)
{
// take some action
}
// Rest of the function
}
2. Pointers may be reassigned to refer to different objects
A pointer may point to any variable of its type and may change. But a reference always refers to the same object to which it is initialized.
int a = 5;
int b = 10;
int *ptr = &a; // ptr points to a and *ptr = 5
ptr = &b; // ptr points to b and *ptr=10
int &ref = a; // ref is just another name for a. ref=5
ref = b; // ref will NOT refer to b but value of a & ref will be changed to 10 (same as a=b)
Hence you should use them keeping this property in mind.
3. Copy constructorThe copy constructor only accepts a reference and not a pointer to an object
4. Operator overloadingWhen we overload certain operators, the reference becomes the obvious choice. For example, the Assignment operator returns a reference to the object to which the value is assigned. This is to make the assignment like below possible:
a = b = 5;
If a and b are int then it will be handled by the compiler, but if they are user-defined types, and we are overloading the assignment operator, then that function should return a reference (and not a pointer).
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment