Where do things go?

Now that we know how to define a class, and how to implement its methods, lets look at where things go.

Note: These things are conventions in real life, but for me (and that means for you in this class) they are unbreakable rules!

Figure 11.5. Overview of a Class in C++
Overview of a Class in C++

Rules:

  • The class defintion belongs in a header file (.h), that has the exact same name and capitalization of the class. Example: Hello.h

  • The class implementation belongs in a source file (.cpp) that has the exact same name and capitalization of the class. Example: Hello.cpp

  • The header file will be guared against multiple inclusion with the #ifndef ... #define .. #endif construct

  • The source file will always include its own class definition (e.g. #include "Hello.h" )

This way, there are always 2 files for each class (exception: pure virtual classes).

Note: If you use eclipse you can have ecplise create these files for you (say New / Class)

To start the program, we still need a main() function. This function should go into its own file, preferably something like "main.cpp". In good OO programs this function is very short! Example:

#include "SomeClass.h"

int main() 
{
  SomeClass *myInstance = new SomeClass();
  myInstance->start();
  delete myInstance;
  return 0;
}

Remember to always include things where there are used!

Because I love graphics, here's another graphic showing the same thing:

Figure 11.6. A C++ program
A C++ program

But enough theory, here is a complete example:

Example 11.1. Hello.h
#ifndef HELLO_H_
#define HELLO_H_

class Hello
{
private:
  bool formal;
public:
  void greeting();
  void setFormal(bool f);
  bool getFormal();
};

#endif /*HELLO_H_*/

Example 11.2. Hello.cpp
#include "Hello.h"
#include <iostream>
using namespace std;

void Hello::greeting()
{
  if (formal)
    cout << "Hello, nice to meet you!" << endl;
  else 
    cout << "What's up?" << endl;
}

void Hello::setFormal(bool f)
{
  formal = f;
}

bool Hello::getFormal()
{
  return formal;
}

Example 11.3. main.cpp
#include "Hello.h"

int main()
{
  Hello *h = new Hello();
  h->setFormal(true);
  h->greeting();
  delete h;
  return 0;
}