Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: "const" in front of a class method

Tags:

c++

Taking for example this method declaration:

const Vector Vector::operator - ( const Vector& other ) const;

I know that the second const makes the Vector passed as an argument immutable, and that the last const declares that the method does not change the current instance of the Vector class....

  • But what exactly does the first const mean or lead to?
like image 815
Yukon Avatar asked Feb 20 '11 21:02

Yukon


People also ask

What does const in front of a function mean?

const after member function indicates that data is a constant member function and in this member function no data members are modified.

Can const be used before a function name?

A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error. When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.

What does const before a function mean?

const before a function means that the return parameter is const , which only really makes sense if you return a reference or a pointer. const after the function means that the function is part of a class and cant change any members of that class. Also const objects are only allowed to call these const functions.

What does it mean for a method to be const C++?

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.


2 Answers

It is an outdated security measure to prevent nonsense code like a - b = c to compile.

(I say "outdated" because it prevents move semantics which only works with non-const rvalues.)

like image 117
fredoverflow Avatar answered Sep 29 '22 21:09

fredoverflow


The first const means that this operator will return a constant Vector object.

like image 43
Wheatevo Avatar answered Sep 29 '22 21:09

Wheatevo