Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 912
oek Avatar asked Oct 29 '18 08:10

oek


People also ask

How do you implement header files in C?

In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.

Do templated functions need to be 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.

Can I write functions in header file?

The answer to the above is yes. header files are simply files in which you can declare your own functions that you can use in your main program or these can be used while writing large C programs. NOTE:Header files generally contain definitions of data types, function prototypes and C preprocessor commands.

Why are templates implemented in the header file?

Templates are often used in headers because the compiler needs to instantiate different versions of the code, depending on the parameters given/deduced for template parameters, and it's easier (as a programmer) to let the compiler recompile the same code multiple times and deduplicate later.


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.

like image 92
lubgr Avatar answered Oct 19 '22 01:10

lubgr