const at the beginning and const at the end
Please explain why const is done at the beginning and const at the end, and what is the difference in general?
const Cash Product::GetPrice() const { return price; }
2 answers
Using const
at the beginning of a method declaration binds it to the type of the return value, i.e. it says that you are returning a constant object from the method.
When you use const
at the end of a method declaration, the method itself becomes constant (without changing anything in the object) and, as a result, is available for calling through constant objects.
This ad
const Cash Product::GetPrice() const { return price; }
Defines a non-static member function of the class named GetPrice
for the class Product
.
The first qualifier const
refers to the return value of the function, that is, to an object of type Cash
.
The const
qualifier after the list of parameters refers to the function itself and indicates that the function does not modify the object of type Product
for which it is called.
For example, if an object of type Product
is declared as a constant object, then it is not allowed to call non-static member functions of the class that are declared without the const
qualifier.
Also, for non-static class member functions, you can specify reference qualifiers that determine for which type of reference (lvalur or rvalue) to an object of the class, the corresponding non-static class member function can be called.
Below is a demo program
#include <iostream>
struct Cash
{
Cash( unsigned int value ) : value( value )
{
}
unsigned int value;
};
struct Product
{
Product( unsigned int price ) : price( price )
{
}
const Cash GetPrice() &
{
std::cout << " - const Cash Product::GetPrice() & is called - ";
return price + 10;
}
const Cash GetPrice() const &
{
std::cout << " - const Cash Product::GetPrice() const & is called - ";
return price;
}
const Cash GetPrice() const &&
{
std::cout << " - const Cash Product::GetPrice() const && is called - ";
return price;
}
unsigned int price;
};
int main()
{
const Product p1( 10 );
std::cout << "cash" << p1.GetPrice().value << '\n';
Product p2( 10 );
std::cout << "cash" << p2.GetPrice().value << '\n';
std::cout << "cash" << Product( 10 ).GetPrice().value << '\n';
}
Program output to the console:
cash - const Cash Product::GetPrice() const & is called - 10
cash - const Cash Product::GetPrice() & is called - 20
cash - const Cash Product::GetPrice() const && is called - 10
Since the object p1
is constant, then a function with qualifiers const &
is called for it.
The p2
object is not constant, and a function with the reference qualifier &
is called for it.
The last function call uses a temporary object, so a function with the qualifiers const &&
is called for it.