Sunday, September 22, 2019 | Toby Opferman
 

Object Oriented Programming

Toby Opferman
http://www.opferman.net
programming@opferman.net



                                  Beginner's
                        Object Oriented Programming in C++

        You may hear a lot of people say that C++ is only semi-object
oriented.  That is primarily because of the existance of other languages
such as small talk.  Also, since C++ inherited C, it has a top down
structure.  In this tutorial, I am not going to talk about that.  I
assume you know C already in this tutorial since C++ builds upon C.
I am not going to teach you the new standard C++ library or STL.
What I will teach you is OO in C++, what objects are and how they
work.  Once you understand this, you can pick up a reference manual
and look at the command syntax.  Learning commands is something
for a reference manual.  Implementation is something that needs a
tutorial and I assume everyone has already programmed and can implement
loops and conditional statements.

Quick Overview.
        This is a quick "What's differnt/new in C++ from C?" reference.

TypeCasting isn't as loose as in C.  You may have to type cast
a lot of your variables with (int) or int().  C++ provides a new
way to convert  datatype().  example:

float x;
int y;

y = (int)x;
y = int(x);
They perform practically the same operation.

In C, you HAD to define variables at the beginning of a block.
In C++, you can define variables anywhere.
c:

int y, x;
y = 10;
for(x = 0; x < 10; x++)
  printf("\n");

c++:

int y;
y = 10;
for(int x= 0; x < 10; x++)
  printf("\n");


Although I still declare all my variables at the beginning of
a block for readability and neat programming, but you do have the
option to be a pig.

Memory Allocation:
In C you used malloc() and free().  In C++, you can do
the same, but now there are also operators.

new and delete.

C:
char *x;

x = (char *)malloc(sizeof(char)*10);

free(x);

C++:
char *x;

x = new char[10];

delete[] x;

As you see, you can use [] to allocate a block of memory.
or to allocate just one char:

x = new char;

delete x;


If you know C, those should be self explanitory.

The rest you should be able to pick up as you program with C++.
I told you that was quick and dirty!


Learning Objects
        Ok, first I want you to forget about programming.  Think of
an old fashioned alarm clock.  The kind you probably see in cartoons,
the round analog clocks with the bells on the top.  Picture that, but
forget about the alarm part.  For theory purposes, let's say it's
indestructable too.  What do you do to tell time?  Do you physically
grab the Minute and Hour hands and look at them? No.  You look through
the glass they are encapsulted in.  How do you change the time?  Do
you physically grab the hour hand and second hand and move them?  No,
there is a knob on the back of the alarm clock that you use to change
the time.  This is data encapsulation.


// Class Clock
class Clock {

  public:
    int SeeTimeHours(void);
    int SeeTimeMinutes(void);
    void SetTime(int, int);

  private:
    int Hour, Minutes;
};

 // See The Hours
 int Clock::SeeTimeHours(void)
{
  return Hour;
}

 // See The Minutes
 int Clock::SeeTimeMinutes(void)
{
  return Minutes;
}

 // Set The Time
 void Clock::SetTime(int H, int M)
{
  Hour = H;
  Minutes = M;
}

  Don't worry if you don't understand the syntax, I will explian it.
I just want you to understand how it relates to the physical clock.
'class' is closely related to a C 'struct'.

class <Object Name> {

This is how you declare your object.
  public:

The public keyword means that the following functions and
variables are able to be accessed by the program directly
through the object (You will see in a minute).

  private:

Private means that only the object itself can use/access
the variables.

 int main(void)
{
  Clock MyClock;

  Now, you have defined a variable called "MyClock" to be
  an object of type Clock.  You can:

  MyClock.SetTime(9, 30);

  Set The Time.
  (NOTICE the fact that you access the members of the class
    same way as you did with C structs.)
                  
  printf("%d:%d\n", MyClock.SeeHours(), MyClock.SeeMinutes());

  And See the time.  Just like in the real clock.

  You cannot do this:
  MyClock.Hour = 8;

  Hour is under "private" just as the hour hand on the real clock
  is protected behind glass and you cannot physically move it, but
  you need to call "SetTime()" which on the clock is a knob on the
  back.  To see the time, you need to call "SeeHours(), SeeMinutes()"
  which on the real clock is just looking into the glass at the Hours
  and Minutes.  This is exactly the same thing, execpt it's "abstract".

  You may have heard the buzz word "Abstract Data Type".  It shouldn't
  scare you.  Programming is abstract. Abstract just means you have one
  thing represent another. That thing may act, look and seem like it's
  real counter part (If it has one), but it's not.  The "class Clock"
  is an abstract data type.  It behaves like a clock, but it's not, it's
  just code.

  An Example:

  If you were going to give someone directions to your house, you may do
  this:

   Oak            /\ My House
  (Tree)  \      /  \
           \     |  |
      ---------------
 
  Say you drew a circle to represent an Oak tree.  That is not an
  oak tree, it's a circle that says Oak tree.  That is abstraction.
  You referr to it as an oak tree, you even picture it in your head
  as an oak tree.  You say "Turn Left near the oak tree" and you point
  to it.  It's not an oak tree though, it's an abstract Idea.  It's a
  circle you imagine to be an oak tree.

 They Object Syntax.
 class <Object Name> {
   public:
     <Data, Functions>
   private:
     <Data, Functions>
 } ;

 Functions are defined as:
<return Type> <ObjectName>::<FunctionName>(Parms)
{
  code
}

The :: is called the scope resolution operator. It comes with a
new bag of tricks that you will learn as you program.  As Objects
make more sense, what :: does becomes more clear.  Just think of
it as "belongs".   Example:


 // Set The Time
 void Clock::SetTime(int H, int M)
{
  Hour = H;
  Minutes = M;
}

Function "SetTime" belongs to object "Clock".

That's how you can think of it.

One last thing.

CONSTRUCTORS
  These are in the public part of the class and they are not called
directly and they have no return value.  They initialize the class
when it is declared.


class Example {
  public:
    Example(void);
  private:
    int x;
} ;

  Example::Example(void)
{
  x = 0;
}

When you declare an "Example" object:

Example One;

It auto calls Example().  This is so you can Initialize your
varaibles and what ever else you need to do when the class is
first created.


Let's look at one complete example.

The Problem:
 Sam needs a program to keep track of his piggy bank.  Since it
is inclosed, he can never see how much money is in there.  So, he
wants to add functionality to his piggy bank "SeeMoney" and he will
enter how much he takes and how much he inserts so he will
be able to know how much is in his piggy bank.


The Solution:
 #include <stdio.h>

 // The Piggy Bank Class
 class PiggyBank {
    public:
      PiggyBank(void);
      int TakeMoney(float);
      void InsertMoney(float);
      float SeeMoney(void);
    private:
      float Money;
} ;

 // Initialize his money to zero
 PiggyBank::PiggyBank(void)
{
  Money = 0;
}

 // Enter amount to withdrawl, returns a 0 if not enough money.
 int PiggyBank::TakeMoney(float Amount)
{
  if(Amount > Money)
    return 0;

  // Take Out Money
  Money -= Amount;

  return 1;

}

 // Enter Amount to insert
 void PiggyBank::InsertMoney(float Amount)
{
  Money += Amount;
}

 // See How much money in the bank
 float PiggyBank::SeeMoney(void)
{
  return Money;
}

 // The implementation
 int main(void)
{
  PiggyBank SamsBank;
  // Now, Sam has his piggy bank now.

  // He puts $10 in
  SamsBank.InsertMoney(10.00);

  // He takes money
  if(SamsBank.TakeMoney(5.00) == 0)
     printf("Not Enough Money\n");

  // He looks at his money
  printf("Sam has $%5.2f\n", SamsBank.SeeMoney());

Sam is now a happy boy.  His PiggyBank abstract data type (ADT)
represents his real life piggy bank, but he has added the functionality
of being able to see how much money is inside it and this helps him
out instead of having to tear it apart and count it physically.


That covers the basics of objects.  There are a lot more advanced topics
to be covered.  Once you get a better grip on things, you should continue
with Inheritence and operator overloading.  Make a few programs using objects,
find things to encapsulate, etc.

That is it.  I tried to keep things simple and I hope you have learned
the basics of Objects.  If not, there are other resources on the web or
books that you can purchase to learn OOP.
 
About Toby Opferman

Professional software engineer with over 15 years...

Learn more »
Codeproject Articles

Programming related articles...

Articles »
Resume

Resume »
Contact

Email: codeproject(at)opferman(dot)com