Sunday, June 07, 2009

How to Separate Interface From Implementation

Well I've finally managed to see how to separate implementation from interface. The basic idea is pretty simple and that only took about a minuet to understand. This was mainly due the fact that it was easy to find lots of examples online. Really the only problem was that they didn't tell you HOW to use this to make a functional program.

So I'll just put together a quick "how-to", where I'll walk through a simple example.

We will create a class called Base, below is the base.h file.


#ifndef BASE_H
#define BASE_H
class Base
{
int value;
public:
void set_value(int);
int get_value();
};
#endif

So that's the interface for our class, not to create the implementation. This will be in a file called base.cpp

#include "base.h"
void Base::set_value(int x)
{
this->value=x;
}
int Base::get_value()
{
return this->value;
}

Finally here is the main program. Since we don't want to be original we shall just call it main.cpp and it looks something like this.

#include< iostream >
#include "base.h"
using namespace std;
int main()
{
Base X;
X.set_value(120);
cout<< X.get_value()<< endl;
}

Now to we create an object file from base.cpp by entering g++ -c base.cpp into the terminal. Then to link this with main.cpp we type g++ main.cpp base.o into the terminal. If all has worked you should see the number 120 printed to the screen when you run your program. (with ./a.out in cause you were wondering)

1 comment:

Anonymous said...

Thank you for leaving the g++ commands. That solved my issues with my own code. Thanks again for the help!