Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const method - repeat in implementation?

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.

like image 785
M.M Avatar asked Jul 04 '16 10:07

M.M


People also ask

What does a const method mean?

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.

When should a method be const?

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.

Can a const method call a non const method?

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.

What does const after method mean?

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.


2 Answers

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 constness. 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 volatileness too.

like image 158
Mattia F. Avatar answered Sep 18 '22 15:09

Mattia F.


You absolutely must include the const qualifier in the implementation.

It is possible to overload functions according to their constness. In fact this is a very important part of the language.

like image 34
Bathsheba Avatar answered Sep 21 '22 15:09

Bathsheba