In C++, how to write full implementation in header for classes and functions (possibly templated)

Viewed 143

I usually declare in header file and implement in cpp file, but now I am doing an assignment, and, apparently for brevity, the instructor doesn't want me to do that, but insists that I write all the code in header files.

So, what is the best way to do that?

For classes, should I declare everything first, and then go to the bottom of the page and start implementing?

class myClass 
{
void myMethod();
}

void myClass::myMethod() { //.... }

or should I just implement as I declare

class myClass 
{
void myMethod() { //... } ;
}

What about free functions?

And when should I write "inline"?

1 Answers

or should I just implement as I declare

Yes, implement them in class, not out of class. When the (questionable) reasoning of your instructor for putting everything into a header refers to brevity, this is obviously the way to go.

What about free functions?

Same as with member functions, define them on the go.

And when should I write "inline"?

You should add inline to all ordinary free functions. It's unnecessary for function templates or in-class member function definitions. When you can use C++17, consider inline variables, too.

Related