Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I use explicit constructor, do I need to put the keyword in both .h and .cpp files?

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?

like image 921
chester89 Avatar asked Nov 07 '08 21:11

chester89


People also ask

Should constructor be defined in header file?

In both cases the constructor is inline. The only correct way to make it a regular out-of-line function would be to define it in the implementation file, not in the header.

Should I include in header or cpp?

To minimize the potential for errors, C++ has adopted the convention of using header files to contain declarations. You make the declarations in a header file, then use the #include directive in every .cpp file or other header file that requires that declaration.

Do templates need to be defined in header?

To have all the information available, current compilers tend to require that a template must be fully defined whenever it is used. That includes all of its member functions and all template functions called from those. Consequently, template writers tend to place template definition in header files.

What is the point of .h files C++?

Why Do You Use Header Files? Header files are used in C++ so that you don't have to write the code for every single thing. It helps to reduce the complexity and number of lines of code. It also gives you the benefit of reusing the functions that are declared in header files to different .


1 Answers

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) {}
like image 135
Greg Hewgill Avatar answered Sep 29 '22 22:09

Greg Hewgill