Search code examples
c++classmethodsconstants

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.


Solution

  • 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 is 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.