Tom
Tom

Reputation: 9663

c++ constant function declaration variants?

Are all of the below declarations the same? If so, what is the standard way to declare a constant function?

const SparseMatrix transpose();

SparseMatrix transpose() const;

const SparseMatrix transpose() const;

Upvotes: 2

Views: 208

Answers (3)

David G
David G

Reputation: 96875

The const on the left of the function name means the object that is returned cannot be modified. The const on the right means the method is apart of a class and does not modify any of its data members. Unless or course any of its data members are declared with the mutable keyword, in which case modification thereof is permitted despite a const guard.

The placement of the const keyword is unimportant when the return type of the function is of non-pointer type:

 T const f(); // same as const T f();

However, note that the placement of the const keyword matters when using a pointer as the return type. For example:

const T* f();

This method returns a pointer to a const T. That is, what it points to is immutable. So you cannot do an assignment through a dereference of the returned pointer:

T* x = f();

*x = y; // error: assignment of read-only location '*(const T*)x'

When const is placed on the immediate right of the return type (that is a pointer), it means the pointer is const and cannot be changed.

T* const f();

int main()
{
    T* x const;

    x = f(); // error: assignment of read-only variable 'x'
}

Furthermore, if we have const on both sides of a pointer return type, and have const denoting "no modification of class members", then it's read as the following:

const T* const f() const;

A const member function named f that returns a const pointer to a const T

Upvotes: 7

kwen
kwen

Reputation: 41

1) return a const value 2) const function, no member changes inside it 3) 1)+2)

Upvotes: 0

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33954

The first one will return a SparseMatrix that is const and cant be changed.

The second one declares a function that returns a SparseMatrix and assures the function will not change any class variables (assuming it is a member function, otherwise it wouldnt make sense with this deceleration) except for mutable members.

The final one does both.

Upvotes: 4

Related Questions