Igracx33
Igracx33

Reputation: 387

Why put const (...)& in C++

I was wondering - why is putting const (...)& in C++ a good idea? I found this code in some class tutorials. I understand that const is making something constant and it can't be changed, while & is passing it to the function. Why do both? If I can't change something, why should I be passing it to the function?

Here is an example:

class CVector {
      public:
        int x,y;
        CVector () {};
        CVector (int a,int b) : x(a), y(b) {}
        CVector operator + (const CVector&);
    };

    CVector CVector::operator+ (const CVector& param) { //example 
      CVector temp;
      temp.x = x + param.x;
      temp.y = y + param.y;
      return temp;
    }

Upvotes: 12

Views: 29203

Answers (3)

cse
cse

Reputation: 4104

Why const?: As it is known that const keyword makes the variable immutable(by programmer) in the particular part of code e.g. the function body.
Why &?: The & is used, in this context, for "pass the argument to the parameter as a reference" ( which we say call-by-reference ). Which in effect says: Don't create a new copy of the passed object ( or premitive type ). Since no new copy is creted so the passe argument is use and hence any change made to such parameter-variable will retain even after the function call is ended and will be reflected in the passed argument.

Now, coming to question "Why to use the both?". It is due to following reasons:

  1. To avoide unnecessory copy. For primitive data types call-by-value is not a problem but it is problem for non-primitive data types specially when non-primitive object is large

  2. If we wants to pass some rvalue reference as a function argument then it is necessory that respective parameter should be const-reference i.e. const (...)& otherwie it will be a compilation error. For example, in following code the line fun2( strValue1 + strValue2 ); will produce a compile time error. It can be seen in action here:

    #include <iostream>
    #include <string>
    
    void fun1( const std::string& strParm )
    {
        std::cout << "In [void fun1( const std::string& strParm )] :: " << strParm << std::endl;
    }
    
    
    void fun2( std::string& strParm )
    {
        std::cout << "In [void fun2( std::string& strParm )] :: " << strParm << std::endl;
    }
    
    int main() 
    {
        std::string strValue1 = "Hello ";
        std::string strValue2 = "World!!!";
    
        fun1( strValue1 + strValue2 );  // Ok
        fun2( strValue1 );              // Ok
        fun2( strValue1 + strValue2 );  // Compilation error
    
        return 0;
    }
    

Due to above facts, it is advised to use const-ref whenever possible.

Upvotes: 3

Mostafa Vatanpour
Mostafa Vatanpour

Reputation: 1408

It speeds up the code execution, it offers usage simplicity and it also ensures the caller that you can not change the value of the variable by setting const keyword. It maybe have some other benefits, but I think the performance is the main reason. In this article and related articles, there are many useful things about References in C++.

When you pass a parameter by const type & (pass by reference) like this:

void printStudent(const Student &s) 
{ 
    cout << s.name << "  " << s.address << "  " << s.rollNo; 
} 

int main(){
    Student s1;
    printStudent(s1);
    return 0;
}

Benefits are:

  1. Work easily with object(don't think about pointers)
  2. It does not copy the Student object(so it is fast)
  3. You can not create a new student and assign it to s variable. if you write s=new Student(); the compiler error will happen. So the caller can pass the variable with more confidence.
  4. The parameter can not be null.

Upvotes: 4

CIsForCookies
CIsForCookies

Reputation: 12817

Even though the const is keeping you from changing the value of your parameter, it's better to send a reference to it, rather than send it by value, because, in large objects, sending it by value would require copying it first, which is not necessary when calling by reference

Upvotes: 20

Related Questions