I've been searching a lot for an answer and can´t find it anywere. Say i have:
class foobar{
public:
char foo() const;
};
, in my foobar.h
When I want to implement this class in foobar.cpp should I repeat const
?:
char foobar::foo() const{
//...my code
}
Or can i do (whitout the const
)
char foobar::foo() {
//...my code
}
If this is a duplicate I'm sorry, but no other question truly answered this.
The const means that the method promises not to alter any members of the class. You'd be able to execute the object's members that are so marked, even if the object itself were marked const : const foobar fb; fb.
A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended practice to make as many functions const as possible so that accidental changes to objects are avoided.
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.
This means the method is const, and means the method will not modify any members, it can thus be used in a setting where the object is const.
Yes, you have to include the const
qualifier in the definition.
If you write:
class Foo
{
public:
int f () const;
};
And in implementation file if you write:
int Foo::f () { /*...*/ }
then the compiler will emit an error saying that there is not function with signature int f ()
in the class.
If you put the const
keyword in your implementation file too, it will work.
It it possible to overload functions according to the object const
ness.
Example:
class Foo
{
public:
int foo () { std::cout << "non-const foo!" << std::endl; }
int foo () const { std::cout << "const foo!" << std::endl; }
};
int main ()
{
Foo f;
const Foo cf;
f.foo ();
cf.foo ();
}
The output will be (as expected):
non-const foo!
const foo!
As we did with const
, you can overload a function based on the object volatile
ness too.
You absolutely must include the const
qualifier in the implementation.
It is possible to overload functions according to their const
ness. In fact this is a very important part of the language.
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