Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a const member function, returning a pointer to a non const member variable, why would it be good?

Tags:

c++

I work in a large collaboration (of mostly non-professional programmers, I being one of them). I regularly see examples of the following

void T::DoChanges(I i); // will make changes to internal structure of T (non-const)
V T::GetValue();

class A
{
private:
  T* fMember;
public:
  A(); 
  T* GetMember() const {return fMember;}
}

, Where a use-case would be

A a;
I i;
a->GetMember()->DoChanges(i);
V v = a->GetMember()->GetValue();

This practice violates a tenant drilled into me when i took programming courses, i.e. that const refers not only to the bitwise structure of the class instance, but the internal logical structure. Under this philosophy, the member function should take the following forms:

T* GetMember() {return fMember;}
const T* GetMember() const {return fMember;}

I have heard that some people think that const should only refer to members, speaking strictly using the c++ terminology. How/why would someone argue for this type of practice?

like image 458
qonf Avatar asked Oct 07 '11 10:10

qonf


People also ask

Can a const function return a pointer?

So does it make sense to return a const pointer? It depends on what is const . If the constness refers to the pointed object, yes it does. If you try to make the pointer itself const, it doesn't make sense as it will be ignored.

What will happen if a const object calls a non-const member function?

If the function is non-constant, then the function is allowed to change values of the object on which it is being called. So the compiler doesn't allow to create this chance and prevent you to call a non-constant function on a constant object, as constant object means you cannot change anything of it anymore.

Can a const function return a non-const reference?

If the thing you are returning by reference is logically part of your this object, independent of whether it is physically embedded within your this object, then a const method needs to return by const reference or by value, but not by non-const reference.

Can a const member function call a non-const function?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.


1 Answers

Making the member function gives the indication to the users of this function that it will not modify any class members.
The returned member may or maynot be const but making the member function const gives the users of the class a clear indication of the behavior of function.

like image 99
Alok Save Avatar answered Sep 20 '22 13:09

Alok Save