YkI
YkI

Reputation: 29

class (cpp file & h file) in c++

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

Answers (3)

eran
eran

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:

  1. You create an .h file "myClassA.h" and declare a class called myClassA with a member method called myClassA.SayHello()
  2. You include myClassA.h in another class you create myClassB.cpp, that way myClassB knows that myClassA has a method called SayHello() and it can call it.
  3. If you do not include myClassA.h and you try to call myClassA.SayHello() inside myClassB.cpp, you'll get an error from your compiler, as myClassB does not "know" of myClassA.
  4. If you do include the h file but did not bother to actually create and implement myClassA in myClassA.cpp, you will get a compilation error, since no implementation was found.

Upvotes: 1

Trevor Hickey
Trevor Hickey

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

Omar Freewan
Omar Freewan

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

Related Questions