Differences between C and C++ - references

When moving from C to C++, references or reference types are one of the first novelties we encounter. References are aliases for existing objects in memory.

The general syntax is:

reference_type& name = initializer;

Passing function arguments by a reference

Using a reference type in C++, we can pass function arguments:

  • by reference
  • by const-reference

Function arguments in C and C++

In C, we can pass arguments by value:

void myfn(int arg);

And by a pointer

void myfn(int* p);

In C++, we mainly pass arguments by value:

void myfn(int arg);

and by a const-reference:

void myfn(const MyClass& arg);

Built-in types are passed by value and complex types (classes) are usually passed by const-reference. Passing by const-reference avoids creating costly copies and makes the object a read-only object.

Are references pointers?

References are not pointers. They are a different kind of type. They are simply aliases, another name for something that is already there in memory.

What are references used for?

They are used when declaring function parameters. There, they are mainly used as a const-reference variant, when we want to avoid creating expensive temporary copies:

void myfunction(const std::string& arg);
void myfunction(const MyClass& arg);

Some class operators, such as the copy assignment operator, are of a reference type:

MyClass& operator=(const MyClass& rhs);
Posted on January 26, 2025, by

Slobodan Dmitrovic

Slobodan Dmitrovic is a software development consultant, C++ trainer, and author of several books on C and C++.

Contact Slobodan for C++ training and consultancy services.