6

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"?

3
  • 2
    I typically implement class methods in class. inline required when writing out of class definitions and free functions. Commented Oct 29, 2018 at 9:02
  • 'I usually declare in header file and implement in cpp file' - and that's the way you normally should do it. Sure, if instructor insists... Just return to what is good practice afterwards (suppose you are about to anyway, just wanted to be explicit about). Commented Oct 29, 2018 at 9:48
  • the "possibly templated" in your title suggests that your instructor told you to put everything in the header for a good reason: templates can only be implemented in header files Commented Oct 29, 2018 at 10:37

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.