21

Actually my question is all in the title.
Anyway:
I have a class and I use explicit constructor:
.h

class MyClass
{
  public:
    explicit MyClass(const string& s): query(s) {}
  private:
   string query;
}

Is it obligatory or not to put explicit keyword in implementation(.cpp) file?

Martin York
  • 257,169
  • 86
  • 333
  • 562
chester89
  • 8,328
  • 17
  • 68
  • 113

2 Answers2

28

No, it is not. The explicit keyword is only permitted in the header. My gcc says:

test.cpp:6: error: only declarations of constructors can be 'explicit'

for the following code:

class foo {
public:
    explicit foo(int);
};

explicit foo::foo(int) {}
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0

Re the followup question (which you really should have submitted as a separate question), the initialization list goes with the constructor's implementation (its function body), which might be in either the header or the cpp file.

Joe Ganley
  • 592
  • 5
  • 8