Tutorial 8 – More Classes

Following on from the last tutorial we’re now going to start adding some interesting things to our class. Open up your “MyObject” header file and change the code to look like this:

class MyObject
    void PrintAndAdd(void);

Now we have a class that has a public function called “PrintAndAdd” and a private member variable called “memberVariable”. For more information on public, private and protected qualifiers see Encapsulation.
Since we’ve declared some new stuff in our header file, we should implement it in the code file:

#include "MyObject.h"

    memberVariable = 0;



void MyObject::PrintAndAdd(void)
    printf("%d\n", memberVariable++);

Now the constructor makes sure that all of it’s (one) member variables are initialised and we have implemented a function which, as you might have guessed, prints out the value of the member variable and then adds to it.

Lets try using this class in our main function:

#include "MyObject.h"

int main()
    MyObject testObject;


    return 0;

So we construct the object as before, it’s “PrintAndAdd” function is called 3 times and then the main function ends and “testObject” is destroyed. Run the program and you should get the output:

And that’s how easy it is to use classes; objects which can contain their own data and functionality in one neat package!

  1. No comments yet.
  1. No trackbacks yet.

Tell me what you think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: