Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const parameter in function prototype [duplicate]

Tags:

c++

constants

I am trying to understand a piece of C++ code and I have come to a point that I don't understand what the following means:

The following is defined in the function prototype file, aka (.h)

What I am perplexed about, is the const parameter:

ofMesh getImageMesh() const;

I mean, the function/method returns a class of ofMesh, getImageMesh() has no parameters and then const follows. Why is "const" used like this?

like image 764
Nick_K Avatar asked Sep 14 '26 15:09

Nick_K


2 Answers

That's a const method, meaning you can call it on const objects and it won't modify non-mutable members, nor will it call other non-const methods.

struct X
{
    void foo();
    int x;
    void goo() const;
};

void X::goo() const
{
   x = 3;  //illegal
   foo();  //illegal
}

//...
const X x;
x.foo();   //illegal
x.goo();   //OKAY
like image 135
Luchian Grigore Avatar answered Sep 17 '26 05:09

Luchian Grigore


Basically, it means that method will not modify the state of an instance of that class. This means that it will also not call other members that would change the state of an instance of the class.

OK:

class Foo
{
   int m_foo;
   int GetFoo() const
   {
       return m_foo;
   }
}

Compile error:

class Foo
{
   int m_foo;
   int GetFoo() const
   {
       m_foo += 1;
       return m_foo;
   }
}

There are deeper considerations, such as performance benefits when passing by reference - if you want to go deeper, the term to search for is 'const correctness'.

like image 41
acarlon Avatar answered Sep 17 '26 07:09

acarlon