stakx stakx - 1 year ago 42
C++ Question

When defining a member function out-of-line, which qualifiers must appear in the declaration / definition / both?

I am almost sure this has been asked before. Unfortunately, my C++ has become so rusty that I don't even know what to search for.

Is there an easy-to-remember rule of thumb that would tell me which qualifiers (

, etc.) must appear (a) only in the declaration, (b) only in the definition, (c) both in the declaration and definition when I define a member function out-of-line?


struct Geometry {

virtual Geometry* clone() const = 0;

struct Point2 : public Geometry {

virtual Point2* clone() const override { … }

If I wanted to define
out-of-line, trial and error leads me to believe that this would be the correct code:

struct Point2 : public Geometry {

virtual Point2* clone() const override;

Point2* Point2::clone() const { … }

  • The
    qualifiers may appear only in the declaration.

  • const
    must appear in both the declaration and definition.

I would not want to rely on trial and error forever. But I want to be explicit about qualifiers (i.e. repeat them even if e.g. they are implied by a base class.) Is there a general rule which qualifier has to go exactly where, or are the rules different for each of them?

Answer Source

General rule is that when removing a qualifier produces a different function overload, that qualifier must appear in both places. All other qualifiers stay in the declaration.

The two qualifiers that must appear in both places are const and the two kinds of reference qualifiers, which appear in the C++11 standard:

void foo() const;
void foo() &;
void foo() &&;

All other qualifiers stay in the declaration.