Public Group

# Just wondering

This topic is 5410 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a small problem when reading others source C++ code. The seperation of the code into seperate .C++/h files gets me confused. Was wondering if there was any tutorials that explained how things where sepperated? Im starting to get it but would like a little help getting it completely down.

##### Share on other sites
i'll give it a shot since i was stuck there for a while and no one seemed to provide a decent explanation (didn't ask here though =))

i assume you know what the #include preprocessor directive does, if not its easy to look that up.

you'll usually have a .cpp and an .h file with the same name, like this:

myclass.cpp
myclass.h

called it myclass because i like to keep each class in a separate file, though C++ doesn't force you to do this (i think java does... while its neat that way its nice to have options)

So, at the top of myclass.cpp you'd have:

#include myclass.h

//methods implementation

and in myclass.h you'd have:

#include <stdlib.h> // other libraries you
#include <somethingelse.h> // might use for this class

class myclass { ... } // declaration of class

--hope that helps! (forgot what the code tags are like heh)

##### Share on other sites
Thanks but I was asking more on what is generally put in the .cpp file and what was put in the .h

##### Share on other sites
Declarations go in the .h, definitions in the .cpp. For example, for regular functions, in the .h file you would have
void SayHi();

In the .cpp file you might have
void SayHi() { cout << "Hello World!" << endl; }

There are exceptions... for example for inline functions and templated classes the entire thing often has to go in the .h

##### Share on other sites
Like everyone said, declarations in .h and definitions in .cpp

Example:

Car.h

class Car
{
Car();
int speed;
int acceleration;
void move();
void stop();
};

In declarations, you just name the variables and member functions.

Car.cpp

#include "Car.h"

Car::Car()
{
speed = 0;
acceleration = 10;
}

void Car::move()
{
speed += acceleration;
}

void Car::stop()
{
speed = 0;
}

In definitions, you actually define what each of the functions do.

Hope that clears it up for u.

##### Share on other sites
Yes it does. ^_^ Thanks

• 17
• 10
• 21
• 16
• 9