3

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?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
Nick_K
  • 541
  • 6
  • 22

3 Answers3

2

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
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • And also this allows compile to do certain optimizations. – mindo Jan 23 '14 at 09:05
  • And the gains in program stability that `const` affords cannot be overestimated. – Bathsheba Jan 23 '14 at 09:06
  • 1
    @mindo: No it doesn't. const and optimisations are separate things. Don't forget that there are the mutable and const_cast keywords, so just because something's marked const doesn't mean it never changes! – Skizz Jan 23 '14 at 09:16
  • You can also call const methods on non-const objects, the object is converted to a const object. You can't call non-const methods on const objects. – Skizz Jan 23 '14 at 09:18
2

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'.

acarlon
  • 16,764
  • 7
  • 75
  • 94
0

The const in this line means that it is a constant function. This implies that it can't modify the object inside it.

Thus, if you declare a member function const, you tell the compiler the function can be called for a const object. A member function that is not specifically declared const is treated as one that will modify data members in an object, and the compiler will not allow you to call it for a const object.

yuvi
  • 1,032
  • 1
  • 12
  • 22