2

One of these days, a fellow user commented on another question of mine: "Everything that you call declarations in your code are actually definitions". I decided to take some time in order to understand the difference between both concepts.

Considering the code below:

test.hpp

class Test
public:
    Test();
};

test.cpp

#include "test.hpp"
Test::Test()
{
    // code
}

main.cpp

#include "test.hpp"
int main()
{
    Teste objTest = Test();
    return 0;
}

Question 1: From my understanding, the header file test.hpp defines a class named Test (based on this answer). Is that correct?

Question 2: My code is based on a common practice (I've seen a number of open-source libraries following that pattern), which seems to be against the rule "headers should contain only declarations; all definitions should be in .cpp file". But is it acceptable? If not, how exactly should one write class declarations/definitions properly?

Community
  • 1
  • 1
Marc.2377
  • 5,840
  • 5
  • 43
  • 75
  • 2
    *"... it goes against the rule "headers should contain only declarations; all definitions should be in .cpp file"* - That is true of **objects** and **functions**. (public) Classes need to be defined in header files. As do *templates* and *inlines*. – Galik Oct 27 '14 at 22:46

2 Answers2

1

Question 1: Yes it is correct.

Question 2: Yes it is acceptable. All definition should be in the .cpp file.

Mosa
  • 373
  • 1
  • 13
1

Answer 1: Technically, yes. Your header file is defining your class, but that's OK. The definition of your class contains the declarations of several class methods, and that's what's important regarding the declare vs. define question.

Answer 2: Correct: Your test.hpp file contains declarations of the test methods, which are defined in your test.cpp file. It's ok for the header file to define a class that consists of method declarations. It doesn't really go against the rule; the rule is correct, but it mainly pertains to the methods of the class.

There are exceptions to this when considering things like inline methods and class forward declarations, but we don't need to worry about those here.

jia103
  • 1,048
  • 2
  • 12
  • 19