C# learning C++ / *.h vs. *.cpp files

My background is in C# and C. I'm learning the syntax for C++. Wondering which code goes in the *.h files and which in the *.cpp files.

Initially I was placing variable declarations and method signatures in the *.h file, and method code in the *.cpp file.

Then I came across this case where moving method SetFunc to the *.cpp file didn't work. I had to put the SetFunc method code in the *.h file, and I was wondering why that was. When should I put the method definition in the *.cpp file and when in the *.h file?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#pragma once
#include "stdafx.h"
#include <functional>
using namespace std;

class MenuItem
{
   private:
      std::function<void()> func_;
   public:
      void SetFunc(std::function<void()> func)
      {
          func_ = (func);
      }
};

I'm also wondering what does the #pragma once line do?

I read somewhere that #include files should be put in the "stdafx.h" file. When should I do that? Which include files should I add to "stdafx.h"?

Also, do #include statements go in the *.h file or the *.cpp file?
Last edited on
Traditionally, unless you want to abuse preprocessor directives, all declarations and template definitions go into header files whereas all definitions of non-templates go into source files.

stdafx.h is a non-standard extension known as pre-compild headers supported by some compilers (most notably MSVC). I recommend not using it.

See also:
https://en.wikipedia.org/wiki/Pragma_once

#include statements go in both headers and source files.
Last edited on
Topic archived. No new replies allowed.