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?
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
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With