Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

constant
c++
return by val

How to return const objects by value in C++

Rabia Zareen

The const object

const is a keyword used for variable values that will remain the same. This means that const tells the compiler to prevent modifying such variable values. The const variable is declared as:

const int val = 5;

An object of the class can also be constant. To demonstrate this, we will declare a constant variable lecture of the class type Time. In the following example, 9 is for hours and 15 is for the minutes variable:

const Time lecture(9,15); 

Return by value

Return by value means when the function’s return statement is executed, the compiler copies the value and sends it to the caller.

However, in return by reference, the compiler sends the address of the variable. It implies that we can change the original value by using the return value, which is not possible to return in the value case.

#include <iostream>
using namespace std;
const int mval()
{ 
   return 1;
}

int main() {
  // your code goes here
  cout << mval;
  return 0;
}
Code for return by value

Returning a const object by value

When the function’s return statement is executed, the compiler copies the object and sends it to the caller. In the code example below, when the main function calls the foo function, it returns the constant object of test by value:

#include <iostream>
using namespace std;
class test
{
	public:
	int id;
	
	//Default Constructor
	test()
	{
		cout << "Default Constructor called" << endl;
		id=5;
	}
};
const test foo(){
    cout<<"foo returning constant object\n";
	const test t1;
	cout << "test id is: " <<t1.id << endl;
  return  t1;
}
int main() {
	foo();
	return 0;
}
Code for return a const object by value

Significance of const object by value

const is most helpful when we need to share the code, but we want to avoid any accidental modifications to the value of an object.

When to avoid const?

When the function is executed, it returns the copy of the constant object. Therefore, in cases where we need to alter the object’s value later, we should avoid using const.

RELATED TAGS

constant
c++
return by val

CONTRIBUTOR

Rabia Zareen
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring