c++ constant function declaration variants? - c++

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;

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

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.

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

Related

Why is const redundant when using const functions C++?

So all modifiers that I have come across in C++ have came prior to the name of the function. Why is const different? Why must it both precede the name and come prior to the function block?
const int getSize() const;
or
const int getSize const {
...
}
These are 2 different usages of the const keyword.
In this case:
const int getSize() {
the function is returning an int that is const, i.e. the return value cannot be modified. This is not very useful, since the const in the return value is going to be ignored (compilers will warn about this). const in the return type is only useful when returning a const*, or a const&.
In this case:
int getSize() const {
this is a const-qualified member function, i.e. this member function can be called on const objects. Also, this guarantees that the object will not be modified, even if it's non-const.
Of course, you can use both of these together:
const int getSize() const {
which is a const-qualified member function that returns a const int.
The const before the function is applied to the return type of the function. The const after is only for member functions and means that the member function is callable on a const object.
As a note returning a const int does not make sense, many compilers will warn that the const gets discarded.

C++ const correctness with reference members

I have a fstream & member in a class, on which I'm calling the seekg function in a const function of the class, and yet the code compiles. I checked, and the seekg is not declared const (nor should it be), so how is this happening?
This is my code:
class Test {
fstream &f;
public:
Test(fstream &f_): f(f_) {}
int fid() const {
f.seekg(5);
return 0;
}
};
It turns out the const does not apply to members that are pointers or references, as stated here.
The best explanation I've seen of this is here where it states that inside const member functions, this is a const T *, where T is the class.
In your example that means that all the const modifier on fid() does is to change this from a Test * to a const Test * inside the function. When you write f., this is accessed as this->f. which is of type fstream & const. The reference is const but what it refers to is not, so calling a function that modifies it causes no problems.
The rule is defined in [expr.ref]/4:
If E2 is declared to have type “reference to T”, then E1.E2 is an lvalue; the type of E1.E2 is T. [...]
In practice you should consider a reference to T, as a const pointer to T with automatic dereferencement. Internaly this is what are reference. And inside the standard, all rules that applies to reference (see [basic.life] for example) are those rules that would apply to a const pointer:
class Test {
fstream * const f;
public:
Test(fstream &f_): f(&f_) {}
int fid() const {
f->seekg(5);
return 0;
}
};

mutable with const pointer in C++

If I use mutable with const pointer like this:
class Test
{
public:
mutable const int* ptr; // OK
};
It's working fine.
But, If I use like this :
class Test
{
public:
mutable int * const ptr; // Error
};
An error :
prog.cpp:6:25: error: const 'ptr' cannot be declared 'mutable'
mutable int * const ptr;
^
prog.cpp: In function 'int main()':
prog.cpp:11:7: error: use of deleted function 'Test::Test()'
Test t;
^
prog.cpp:3:7: note: 'Test::Test()' is implicitly deleted because the default definition would be ill-formed:
class Test
^
prog.cpp:3:7: error: uninitialized const member in 'class Test'
prog.cpp:6:25: note: 'int* const Test::ptr' should be initialized
mutable int * const ptr;
Why does compiler give an error in second case?
const int * ptr;
The first is a pointer to constant data, which means you can change the pointer and where it points to, but you can't change the data it points to.
int * const ptr;
The second is a constant-pointer to non-constant data, which means you must initialize the pointer in your constructor(s) and then you can't make it point anywhere else. The data it points to can be modified though.
The mutable part in both cases applies to the pointer, the actual member variable, not the data it points to. And since the variable can't be both mutable and constant at the same time you should get an error message for that.
The 2nd case causes error because mutable and const can't be mixed; mutable can only be used with non-const data member.
applies to non-static class members of non-reference non-const type and specifies that the member does not affect the externally visible state of the class (as often used for mutexes, memo caches, lazy evaluation, and access instrumentation). mutable members of const class instances are modifiable.
BTW the following code causes the same error.
class Test
{
public:
mutable const int x; // Error;
mutable int const x; // ditto;
};
The 1st case is fine, because const int* is not a const pointer, but a pointer to const. That means it's fine to modify the pointer itself, and you can mark it mutable. (But you can't modify the pointee.)
BTW const pointer to const (e.g. mutable const int* const ptr;) causes the same error too.
struct Test
{
const int* ptr;
};
Translation: "The structure has a member. The member is a pointer. The pointer points to an integer which may not be mutated via the pointer."
The pointer itself may be mutated though, to point to a different const int.
It's probably simpler if we pick a non-reference type, so you can separate the types of the member (in your example a pointer), from the type of the pointed-to object.
struct Test1
{
int value;
};
Now, adding the mutable keyword to get
struct Test2
{
mutable int value;
};
just means we're allowed to mutate the member even when the structure itself is otherwise const.
In other words, all of this is OK in both cases:
Test1 a { 123 };
Test2 b { 123 };
// now mutate the object through a non-const reference
a.value = 42;
b.value = 42;
but this is different:
const Test1& ca = a;
ca.value = 69; // NO, a member of a const object is const
const Test2& cb = b;
cb.value = 69; // OK, a mutable member of a const object
So, now that we understand how mutable is being applied, the consider the problematic line:
mutable int * const ptr;
This is saying that ptr is both mutable (able to be mutated even when the object it's a member of is otherwise const) and const (not able to be mutated even when the object it's a member of is otherwise non-const).
The two are obviously contradictory.
The bugs.eclipse.org say's:
The mutable specifier can be applied only to names of class data
members (9.2) and cannot be applied to names declared const or
static, and cannot be applied to reference members.

Can I have a const member function that returns *this and works with non-constant objects?

If I understand correctly, a member function that is not supposed to modify the object should be declared as const to let the users know about the guarantee. Now, what happens when that member function returns the reference to *this? For example:
class C{
public:
C &f() const {return *this;}
};
Inside C::f(), this has the type const C*, so, the following will not compile:
int main() {
C c; // non-constant object!
c.f();
return 0;
}
Of course, we could provide a non-const version of C::f() to work on non-constant objects:
class C{
public:
const C &f() const;
C &f();
};
However, I do not believe that this is what we want. Note that the non-constant version does not change the object, but this promise to the users is not expressed... Am I missing something?
EDIT: Let me just summarize the question for clarity: f() does not modify the object on which it is called, so declaring it as C &f(); without making it a const member is misleading. On the other hand, I do want to be able to call f() on non-const objects. How do I resolve this situation?
EDIT: It comes out from all the discussion that took place in the comments that the question was based on an incorrect understanding of what constness of a function member implies. The correct understanding that I am taking away for myself is:
A member function that returns a non-const reference is intended to allow its users to change the object through the returned reference. Therefore, even though this function does not change the object by itself, there should be no inclination to declare it to be a const member!
Your problem is the original function definition:
C &f() const {return *this;}
here you return a non-const reference to the const object, which would allow changing the const object and would be dangerous, therefore it's forbidden.
If you were to write it as
const C &f() const {return *this;}
would be callable from both const and non-const objects and would always return a const reference.
Of course, we could provide a non-const version of C::f() to work on non-constant objects. However, I do not believe that this is what we want.
Probably that is exactly what you want. It's the only way to return a non-const reference when called on non-const objects and keep const correctness when calling it on const objects.

why must you provide the keyword const in operator overloads

Just curious on why a param has to be a const in operation overloading
CVector& CVector::operator= (const CVector& param)
{
x=param.x;
y=param.y;
return *this;
}
couldn't you have easily done something like this ??
CVector& CVector::operator= (CVector& param) //no const
{
x=param.x;
y=param.y;
return *this;
}
Isn't when something becomes a const, it is unchangeable for the remainder of the applications life ?? How does this differ in operation overloading ???
You don't need const:
#numerical25: Just curious on why a param has to be a const in operation overloading
It's not required, but it is a good design decision.
See the C++ standard Section 12.8-9:
A user-declared copy assignment
operator X::operator= is a non-static
non-template member function of class
X with exactly one parameter of type
X, X&, const X&, volatile X& or const
volatile X&
I think it's a good idea though:
Using a const parameter does seems like a logical design decision to me though because you want to ensure that the other value will not be changed.
It tells other people that use your class that you will not be changing the other value when you say something like: myObject = other; and it enforces this so you can't accidentally change other.
Also if you allowed non const references to the object as the parameter, then you are limiting the amount of objects that can use your function. If it is const it can be used for parameters that are const and non const. If your parameter is non const it can only be used by parameters that are non const.
const only applies to the current reference, not the object:
#numerical25: Isn't when something becomes a const, it is unchangeable for the remainder of the applications life ?? How does this differ in operation overloading ???
A const reference is simply that a reference that is const. It does not change the const-ness of the actual object you are passing in.
An example of non-const operator overloading:
Here is an example of operator overloading where the parameter is not const.
I DO NOT RECOMMEND TO DO THIS THOUGH:
class B
{
public:
const B& operator=(B& other)
{
other.x = 3;
x = other.x;
return *this;
}
int x;
};
void main(int argc, char** argv[])
{
B a;
a.x = 33;
B b;
b.x = 44;
a = b;//both a and b will be changed
return 0;
}
A const parameter is const throughout the function using it, it does not change its constness outside of it.
In this case you want to declare a const argument so that your assignment operator accepts both non-const variables and const variables; the latter case, in particular, includes the result of expressions, which is a temporary const variable and which you generally want to support in assignments.
If you used
CVector& CVector::operator= (CVector& param) // no const
then did this:
const CVector& my_vector = GetMyVector();
some_other_vector = my_vector; // call assignment operator - error!
You'll get an error because my_vector is a const CVector& and that can't be cast to a CVector& (non-const reference). It's just the local reference to it inside the operator= function that is const, not the entire object itself.
You can use the non-const variety, but this has two repercussions, one which is functional, and one which is about what you, as the writer of the function, are telling the user.
1) people calling the function that takes a non-const reference would not be able to call it using a const variable
2) when you have a function argument that's a non-const reference, you're signalling, "I reserver the right to change this". Typically, when a user of your function writes a = b;, he doesn't expect b to change.
Note that there's a third option you could use for this, pass-by-value:
CVector& CVector::operator= (CVector param) //no reference
This doesn't have either of the problems I mention above. However, it's very inefficient. Because of these three factors, passing by reference-to-const is preferred, especially in cases like a vector where copying can be expensive.
For the same reason you would use const anywhere: to ensure that future changes to the method don't inadvertently modify the passed in parameter, to help document the interface to notify callers that it is safe to pass param without risk of it changing, and to allow callers to pass in references that are declared as const in the calling code.
Another reason is to allow for conversions. For example:
string s = "foo";
s = "bar";
Here, an implementation might choose to only provide the assignment operator that takes a const reference to a string as a parameter, and depend on the compiler using a constructor to create a temporary string from the char * "bar". This would not work if the op='s parameter was not const, as you cannot bind a temporary to a non-const reference.
The const qualifier makes the passed parameter (in your example it is 'const CVector& param') as read only. The const qualifier ensures that the parameter (param) is not altered inside the operator=() method.
Without the const qualifier, the following is possible:
CVector& CVector::operator= (CVector& param)
{
x=param.x;
y=param.y;
param.x = 10; // some random value
param.y = 100;
return *this;
}
The above method alters the right hand side operand 'param' after assigning the value to the left hand side operand. The const qualifier helps you not to violate the semantics of the assignment operation.