Reputation: 29
After creating and definition class (in "h file"). How do I decide to create (or not) "cpp file" (only for the class) in addition to "h file" (that belonging to the class)?
Upvotes: 1
Views: 4821
Reputation: 15136
An h file is a descriptor file, that describes the signature of your functions/classes, so that other classes in other cpp files may use it.
You need to think of an h file as a contract. You are declaring an obligation.
Later on, when you decide to implement the cpp, you are fulfilling the obligation.
Other classes/cpp files can rely on your obligation alone, assuming that you will also implement the obligation in a cpp.
For example:
Upvotes: 1
Reputation: 37836
Here is a small example to get you going.
this is Foo's header file. let's call it "foo.h"
#pragma once
#ifndef FOO_H
#define FOO_H
class Foo{
public:
void function();
protected:
private:
};
#endif
This is Foo's source file. Let's call it "foo.cpp"
#include "foo.h"
void Foo::function(){
// ... implement ...
return;
}
compiling them together, we can create an object file. We'll call it "foo.o"
You can use your class in a program provided that you link "foo.o".
Example:
#include "foo.h"
int main(){
Foo foo;
foo.function();
return 0;
}
Upvotes: 2
Reputation: 2678
The best practice is to separate the header and implementation files so you define the class inside the header file .h and implement it inside the .cpp file, this will help you to trace and debugging the errors and shows a clean code ,
Just note in the templates classes it have to be defined in a separate header file to keep your code structured well and clean by separating templates from normal classes
Upvotes: 0