Synfire's Guide to C++

10. Object Oriented Design

This section is what makes C++ so great. OOP or better known as Object Oriented Programming, is what C++ is all about. In this section you will learn about struct, classes, and a little bit of inheritance. These last few things are what will take you from being a small time C++ programmer to a true C++ Coder.

Struct
Struct is a form of OOP that was first established in the C language it's uses were great but it didn't have as much power as the OOP in C++. C++ being the superset of C has carried on the struct tradition and left it be. Struct's syntax is very simple for what it does. You already know about types for varibles such as, int, double, char, etc. but what if you wanted to create your own type. This is what struct does.

#include <iostream.h>
#include <string.h>
#include <fstream.h>

//////////////////////////////////////////
struct Employee
{
 unsigned int Age;
 double Pay;
 char * Name[30];
 char * Title[30];
};
//////////////////////////////////////////

int main()
{
    int Test = 1;
    char * Continue[3];
    char * YesOrNo[3];
    unsigned int i;
    unsigned int Answer;
    Employee Number[200];
    
    ifstream Fin;
    Fin.open("emprecords.dat");
    for(i = 0; !(Fin.eof()); i++)
    {
      Fin >> Number[i].Name;
      Fin >> Number[i].Title;
      Fin >> Number[i].Age;
      Fin >> Number[i].Pay;
    };
    
    cout << "1. View Current Employees" << endl;
    cout << "2. Add New Employee" << endl;
    cout << "What would you like to do? ";
    cin >> Answer;
    if(Answer == 1)
    {
     for(i = 0; !(Number[i] == NULL); i++)
     {
      cout << Number[i].Name << endl;
      cout << Number[i].Title << endl;
      cout << Number[i].Age << endl;
      cout << Number[i].Pay << endl;
      cout << "------------------------------" << endl;
     }
    }
    else if (Answer == 2)
    {
     while (Test)
     {
      cout << "Enter employee\'s name: ";
      cin.get(Number[i].Name, 29);
      cout << "Enter " << Number[i].Name << "\'s age: ";
      cin >> Number[i].Age;
      cout << "What is " << Number[i].Name << "\'s position? ";
      cin.get(Number[i].Title, 29);
      cout << "What does " << Number[i].Name << " get payed? ";
      cin >> Number[i].Pay;
      cout << "Continue?[y/n] ";
      cin >> Continue;
      if (Continue == ("y"||"yes"))
      {
       Test = 1;
       ++i;
      }
      else
      {
       Test = 0;
      }
     }
    }
    else
    {
     cout << "ERROR: Invalid Choice!" << endl;
     goto end;
    }
    cout << "Would you like to save your records? ";
    cin >> YesOrNo;
    if (YesOrNo == ("y"||"yes"))
    {
     ofstream Fout;
     Fout.open("emprecords.dat");
     for(i = 0; Number[i] != NULL; i++)
     {
      Fout << Number[i].Name << endl;
      Fout << Number[i].Title << endl;
      Fout << Number[i].Age << endl;
      Fout << Number[i].Pay << endl;
     }
     Fout.close();
    }
    else
end:    return 0;
}

Okay, I decided to skip the comments and just explain it myself.
I wrote this on the fly for this tutorial so if there are a bunch of bugs then fix it and go on, it is clean enough for the purpose of describing struct, and that is all I care about right now. (If you can't tell it's 12:21 and I've been working on this thing all day, I'm trying to finish it in 1 day flat so just bare with me...)

This program uses just about everything you have learned in this tutorial so far. But the part I want you to focus on is the parts pertaining to struct. First thing I did was create a type called 'Employee' then I gave it several value types that it could store. All this was done on the lines 6 - 12, these are seperated by the comments. Now on line 22 I created an array of the Employee type. Now the Number array holds 200 seperate Employees records in it. On lines 26 - 29 you see how the Number array's elements can be given the information of the type. And that's that for struct. Please study this program in more detail before moving on, though this may seem hard, it is easy compaired to classes and inheritance.

Classes
Classes are what really seperates C++ from C. Struct was a good attempt by Bell Labs to add OOP to the C language, but Stoustrup went even one step further and added classes. Okay we already know about objects from struct, and when we create a class we are creating objects. Classes are like advanced struct's so they aren't the same, but they share alot of the same characteristics. Before I start into syntax I would like to define a few words that you will have to know to understand what the hell I am talking about.

(This part was submitted by Tristan)
In C++ a struct and a class really are the same. In fact the only difference is that by default a struct's members (functions as well as variables) are public while a class's are private. The point really is that a C++ struct is a better and 'backwards compatible' version of the C struct. In C++ a struct and a class really are the same. In fact the only difference is that by default a struct's members (functions as well as variables) are public while a class's are private. The point really is that a C++ struct is a better and 'backwards compatible' version of the C struct.

example:
struct Hello : public SomeBase
{
    Hello() : a(0) { }
    virtual ~Hello() { }

   int GetVal() const { return a; }

private:
   int a;
};
(End of Tristans Submission)

constructor - a constructor is a special function that initializes variables. On simple classes this is done for you by default but you will need to know about them for when we get into some advanced classes

destructor - a destructor is a special funtion that returns memory that you use in you variables, you don't have to have these but there are times that you can't do without them.

public/private - public/private are keywords that define what is allowed to access parts of the class. Public allows all parts of the program access to it's functions and variables. While private only allows the class to access these features. This may sound confusing but it will become clear later on.

Now that I have introduced you to some of the lingo of classes, how about I start this section off by giving you an example class:
#include <iostream.h>

class Fighter
{
 public:
    Fighter (int Level);
    ~Figher();
    char * Name[30];
    void Punch() const;
    void Kick() const;
    void Block() const;
    void Jump() const;
    int SetLevel( int NewLevel);
    int GetLevel();
 private:
    int YourLevel;
};

Fighter::Fighter(int Level)
{
    YourLevel = Level;
}

Fighter::~Fighter() { }

void Fighter::Punch()
{
    cout << "Punches (_(@" << endl;
}

void Fighter::Kick()
{
    cout << "Kickes (__()__(o/^" << endl;
}

void Fighter::Block()
{
    cout << "Blocks :P. o O (WoW, That was close!)" << endl;
}

void Fighter::Jump()
{
    cout << "Jumps . o O (Look I'm a birdie!)" << endl;
}

int Fighter::SetLevel(int NewLevel)
{
    YourLevel = NewLevel;
}

int Fighter::GetLevel()
{
    cout << "You are currently at level " << YourLevel << endl;
    return YourLevel;
}

int main()
{
    Fighter You(0);
    cout << "Enter Your Name: ";
    cin.get(You.Name, 29);
    cout << "Welcome " << You.Name << " to the Gando Dojo!" << endl;
    cout << "Setting level...";
    You.SetLevel(1);
  /******************************************************
  * The rest of your code for the game will go here     *
  * I have written enough to get you started, so lets   *
  * continue with the rest of the tutorial shall we?    *
  * feel free to modify this to create your own console *
  * fighter game, In fact I suggest that you finish     *
  * this code as homework ;) but I'm not one of the new *
  * Slave Drivers at your school so do what you want..  *
  ******************************************************/
    return 0;
}

Erghem, Sorry about all this code, I got just a little carried away.
But, don't worry, I will break this down into parts so that you can better understand it. (The things I do for knowledge! :-/) Well, anyways, lets take a look at the first part of this code.

class Fighter
{
 public:
    Fighter (int Level);
    ~Figher();
    char * Name[30];
    void Punch() const;
    void Kick() const;
    void Block() const;
    void Jump() const;
    int SetLevel( int NewLevel);
    int GetLevel();
 private:
    int YourLevel;
};
This is the main part of our class named Fighter.
The first line of this code, 'class Fighter', creates a class called Fighter, that's easy enough!
Then, on the third line, we define 'public:'. This makes the codes up to the 'private:' command, available to the rest of the program for altering.

Skipping over these commands to the 'private:' command, we come to the part of the class that only this class can alter. In other words, you cant make a call from main() to YourLevel, but you can create a call from main() to GetLevel(), and since GetLevel() is in the class it has access to YourLevel.

Understand? I'll assume you do.

Now back up to the code within 'public:', we can define arrays variables, just like struct, but, unlike struct, we can also define functions. These functions are called 'Member Functions'. Notice that the first two things in the class are two functions named after the class, the second with a leading ~. These are the constructor and destructor. I created the constructor that automatically sets the Level when the variable is created, and the destructor is just NULL because I have no use for it.
In either case you can add code to the constructor and destructor, or you can just leave them blank, this is all up to you, and weither or not you want to have the constructor automatically set variables in the program. Now on the Last line where the block ends you will notice the ';' after the block. Classes always have a ';' afterwords so just always put one.

You also probably notice something different about lines 7 - 10,
yes const is on the wrong side. This is because when I define something constant in a class, I always put it at the end, that came from a set of 'house rules' I picked up from a job I had. Getting side tracked a bit here it is important to realize that, when coding professionaly, some companies have a 'house standard' that they want their coders to use. This is a set of syntax rules on how your programs should look, the reason for this is that it makes it easier for many people to work on the same project.

Now, back to classes. The next section of code that we come to is a collection of functions like this one:
void Fighter::Punch()
{
    cout << "Punches (_(@" << endl;
}

This is the definition of the Member Functions. This is what is done when the member functions are called. Now when you created the Punch() member function you were just initializing it. This is the actual function. Here You have to go inside the Fighter class to the Punch() initialization to create your function. Now just like a regular function you first define the return type, in this case 'void'. Then you enter the Functions name, since the function is inside a class you have to enter the class name with "::", those of you familiar with perl will better understand this as an operator that means 'within', followed by the functions name. Then you just create the block as normal.

Going up a little here, you will see the Functions for both the constructor and destructor:
Fighter::Fighter(int Level)
{
    YourLevel = Level;
}

Fighter::~Fighter() { }

These have no return type, and as you can see in the destructor if you don't have code to insert in the block then you can simplify by putting the brackets together after the name, '{ }'. So, one more time, a constructor is a function that is automatically called when the variable is created, and a destructor is automatically called when it is deleted. I know I'm drilling this into your head but damnit it's important!

Now moving on down to our main() function, you see the code:
int main()
{
    Fighter You(0);
    cout << "Enter Your Name: ";
    cin.get(You.Name, 29);
    cout << "Welcome " << You.Name << " to the Gando Dojo!" << endl;
    cout << "Setting level...";
    You.SetLevel(1);
On the first line of the block you see the object You created. This is done with a '(0)' because the constructor needs the initial level. If the constructor didn't contain code, and didn't need arguments, then you would just type, 'Fighter You;' as though it was a variable. On the third line of the block you see the Name array is used, when you use a part of an object you first type the object name 'You' followed by a period, just as in struct, then followed by the member function or variable or whatever. So what has happend is the You object's Name array has just been given the value of the users input. Then on the forth line of the block we see how to print the contents of the You objects Name array. Lastly on the final line we see the program makes a call to the member function and passes 1 as the arguments. I know this seems confusing, but it really gets easier each time you look at it. So go over it a couple of times.

While I'm still on the subject of classes, Remember how I made an array of 200 Employee's using struct, well you can do that in the same syntax with classes.

Inheritance
I'm not gonna spend a long time on this because it is an advanced subject and honestly this is a beginners tutorial. So I will just go over the basics of Single Inheritance.

Okay, lets say you were creating a class for Mammal. And you gave it member functions for Move() and Eat(). Then you decided that you wanted to create a Dog class with Bark(), WagTail(), and Pant(), then you decided you wanted a Cat class with Meow(), Pur() and ChaseMouse(). Soon you would see a problem, by creating seperate classes, you would have to rewrite the code for the Mammal class into both the Dog class and the Cat class. Luckily Stroustrup added the ability for one class to inherit a trait from another class, just like in real life. This is done adding a simple ':' plus the inherited from classname like so.
class Mammal
{
 public:
    Mammal(){}
    ~Mammal(){}
    int Move();
    int Eat();
 protected:
    int itsAge;
};

class Dog : Mammal
{
 public:
    Dog(){}
    ~Dog(){}
    void WagTail();
    void Bark();
    void SetBreed(char * Breed[9]){ strncpy(ItsBreed, Breed, 9); }
 protected:
    char * ItsBreed[10];
};

Did you notice the 'class Dog : Mammal'? this tells the program that Dog inherits the member functions and Data Types from Mammal. You should also notice that 'private:' was substituted for 'protected:' the reason for this is that 'protected:' allows classes that inherit from that class to have access to it. Now you can go as deep with inheritance as you want but just remember the syntax for classes don't change just because you are using inheritance, and you should have no problem..

Summary
In this section you learned the basics of Object Oriented Design, including Struct, Classes, and Single Inheritance.

ii. Conclusion
I hope this tutorial helped to get you past some of the hurdles that you might come across while learning C++, overall C++ is not a hard language to learn but it gets a bad wrap from people who just don't understand OOP or just can't stand that a new language is getting so much more attraction than languages that have been around for much longer. This is all trivial to me I like C++ and I will stand by it for many years to come. I truly hope that this text in some way has helped you and that you pass it on to help others.

-Synfire-

< < < Lesson 9: File I/O



Have Linux and want to learn more or just fancy trying it? Read our Linux tutorial.