Results 1 to 2 of 2

Thread: Intermediate C++ Tuturial, Intro to OOP.

  1. #1
    Join Date
    Dec 2007
    Location
    Somewhere in Idaho
    Posts
    480
    Mentioned
    0 Post(s)
    Quoted
    0 Post(s)

    Default Intermediate C++ Tuturial, Intro to OOP.

    Introduction

    C++ is a wonderful language that sometime new programmer never really delve into. It has a great mix of low level capability with many of the features of some of the best higher level languages.

    It was originally based on C. When it was made most people thought the concept of Object Oriented programming, while nice, would never really take off. C++ proved them wrong.

    By now, you have probably dabbled a bit with the C++ language but really want to know what it can do. I hope in my vast ramblings I can teach that to you.

    Requirements
    • You should have writen a "Hello World" program by now.
    • You should know what variables are and how to use them
    • You should know what functions are and how to use them


    What I'll try to teach
    • How to design a OO Program
    • What objects are and how to define them
    • Some good programming style


    Design

    One of the most important aspects of programming is design. Many programmers, new and seasoned, will skip this step to their detriment. It has been shown that the time it takes to design then program is exactly the same as the time it takes to just program. The benefits of a good design are that your code will look neater and be easier to maintain.

    So how do we design an Object oriented program. There are a couple of methods, but this is one that I particularly like.

    The first step is to describe in fairly good detail what your program is supposed to do. So how about some Tic-Tac-Toe?

    Tic-tac-toe, also called noughts and crosses, hugs and kisses, and many other names, is a pencil-and-paper game for two players, O and X, who take turns marking the spaces in a 3×3 grid, usually X going first. The player who succeeds in placing three respective marks in a horizontal, vertical or diagonal row wins the game.
    *Taken from Wikipedia.

    So here is our description. How on earth do you get objects out of that? Well, I hope you where paying attention in English class, because we are going to diagram this description!

    The first step is to Identify all the nouns. They are
    • Tic-Tac-toe
    • noughts and crosses
    • hugs and kisses
    • names
    • pencil-and-paper
    • game
    • players
    • O
    • X
    • spaces
    • grid
    • marks
    • horizontal
    • vertical
    • diagonal
    • row


    Big list of potential objects Huh? Well, you where probably thinking to yourself "There are a lot of redundant objects in there (as well as some adjectives... Just trust me they are supposed to be there)" If you wheren't well, there are.

    So the first step is to remove all objects that mean the same thing. giving a list that might look like this

    • pencil-and-paper
    • game
    • players
    • spaces
    • grid
    • marks
    • row


    When picking out nouns, you want to go for the ones that are the most abstract. We don't want an X and an O object that basically do the same thing.

    You can take many routes from here. The first thing I would do is eliminate worthless objects so to speak. For example. Pencil-and-Paper May serve some purpose in some application, but for this one it pretty much doesn't get us anywhere. Game would be another one that basically describes what the program is supposed to be (not always) so it would be gone.

    So now our list looks like this.
    • players
    • spaces
    • grid
    • marks
    • row


    The next step is describing relation ships. That is, how do objects refer to each-other.

    For example. A grid contains rows, rows contain marks and spaces so you might have a diagram that looks like this
    grid ->
    • row
      • marks
      • spaces


    players

    Or you may have said that spaces have the marks and rows have the spaces. Whatever, it all depends on how you want to look at it. (there is no right answer)

    After you have your relationships down, you will want to start describing what an object does. Again, we look at the description. This time for verbs.

    players -> mark spaces
    Player X -> goes first
    Player -> wins game

    Not much for actions, huh. Sometimes your description will tell you everything you should do. Sometimes it wont.

    After doing some coding this will probably be a little clearer to you. For now, Ill leave it there for (at very least) how to decide what should and shouldn't be an object.

    Making and Object Definition

    Before we can actually make an object we have to define what it is. For example. I can define what a ball is, what it looks like, what it feels like, and what it will do when whacked with a bat. But that doesn't mean that I have a ball or have created one. The same goes with objects, before we can make our ball named bob. we first have to describe what a ball is.

    Code:
    class Ball
    {
    };
    
    int main()
    {
       Ball bob;
    }
    There is a VERY basic class named Ball. Notice that the brackets end with a ";" this is very important syntax note. you cant compile without that stupid semi-colon (yes, I'm bitter).

    Now this ball isn't very exciting, in fact it doesn't do anything at all. But by george we have one.

    On a side note, Class definitions are free. They take no memory until an object of class X is created. So I could define 100 classes but if I never create one I will not use up any memory for the definition.

    Objects, to be considered objects, must have two things. State and behavior. State is a fancy way for saying that it contains variables. Behavior means that it has member functions. (functions specific to the class) So lets give our ball some state.

    Code:
    class Ball
    {
       private:
          double weight;
          double radius;
          char[32] material;
    };
    
    int main()
    {
       Ball bob;
    }
    Now it is slightly more interesting. That ball has things! You are probably looking at the "private:" saying "What the heck?" One of the great features of objects are the ability to have private and public variables and functions. Simply put, a private thing is unaccessible to the outside world. A public thing is accessible to the world.

    In c++ it is considered good practice to keep everything possible private. This delves into whats known as interface.

    Interface is simply that. How you interact with an object. Take a microwave for example. it has a few buttons that you push, and you leave the rest alone (if you know whats good for you). In procedural programming (only using functions) to run a microwave you would push the button. then tell the beeper to signal, then tell the cpu to decide if you should activate the microwave tube, then you tell the timer to start, then you tell the bell to ring when the timer is done. Yikes. Whats worse is in procedural programming there is usually no case so to speak, so all this is happening without protection to the user.

    Object oriented programming takes a different approach. Yes, all that stuff has to be done, but rather then forcing the user to run it all in the correct order, it provides a simple interface and puts a "case" around the rest (the private statement). Yes, you can crack the case open, but why would you want to? You should be able to trust that everything was done correctly and have faith your hot dog will come out hot

    Back to the ball. It has these descriptions, but it doesn't really use them in any meaningful way (in fact, it cant use them). So we need to build our ball so that some of these things become useful. Enter, the constructor.

    Code:
    class Ball
    {
       private:
          double weight;
          double radius;
          char[32] material;
       public:
          Ball();
          Ball(double inWeight, double inRadius, double inMaterial);
    };
    
    Ball::Ball()
    {
       weight = 30.00;
       radius = 4.00;
       material = "plastic";
    }
    
    Ball::Ball(double inWeight, double inRadius, double inMaterial)
    {
       weight = inWeight;
       radius = inRadius;
       material = inMaterial;
    }
    
    int main()
    {
       Ball bob();
       Ball frank(35.23, 28.12, "wood");
    }
    Ok, I did a lot, but it really isn't all that complicated. The first thing you will see is two function prototypes. You probably noticed there are no return types. These functions, with the same name as the class, are known as Constructors. It is their job to get the object setup and ready for work. If you don't define any constructor then one is given to you. It is pretty dumb and doesn't really do much, but if you define any constructor, you loose that base constructor .

    As you can see, the functions are defined outside of the object. They can be defined inside as well, however, you should generally avoid this. The reason is so that you can define the functions in another file then the object description, this makes it that much easier for the user to just glance at the object definition without having to worry about the code that makes it possible.

    you may have noticed the funky Ball:: thing. Basically that just says that this function belongs the the objects of type Ball.

    Lets add a function just for fun.

    Code:
    class Ball
    {
       private:
          double weight;
          double radius;
          char[32] material;
          double getVolume();
       public:
          Ball();
          Ball(double inWeight, double inRadius, double inMaterial);
          double getDensity();
    };
    
    Ball::Ball()
    {
       weight = 30.00;
       radius = 4.00;
       material = "plastic";
    }
    
    Ball::Ball(double inWeight, double inRadius, double inMaterial)
    {
       weight = inWeight;
       radius = inRadius;
       material = inMaterial;
    }
    
    double Ball::getVolume()
    {
       return (radius * radius * radius * (4.0/3.0) * 3.14);
    }
    
    double Ball::getDensity()
    {
       return (weight / this->getVolume());
    }
    
    int main()
    {
       double bobDens;
       double frankDens;
    
       Ball bob();
       Ball frank(35.23, 28.12, "wood");
    
       bobDens = bob.getDensity();
       frankDens = frank.getDensity();
    }
    Well, that was fun. By now you are either seen the beauty that is OOP or going WTF! some recap over what I just changed.

    first I introduced a function. As you probably noticed the function name was prefaced with Ball::. This is just to say that this function belongs to the object type Ball. The next thing I did was add a private function. getVolume. If you tryed to call that function in main you would have been greeted with a nice ambiguous error from your compiler.

    Then theres the getDensity function. You'll notice that it call the function getVolume but it uses some funky notation. the "this->" you saw was a shorthand for a statement that would look like this (*this).getVolume(). "this" is a pointer to the current object in use and it is only available in member functions of the object. (ahh, so thats why you couldn't name a variable this).

    That brings us to the final thing, actually calling a function from an object. the notation is simple. Objectname.function(parameters); you may have even seen it used elsewhere.

    Conclusion

    Hopefully you have learned a little bit about objects and you are starting to see the benfits of OOP. it can be very powerful and flexible once given a shot.
    This is a very, brief intro to it, if enough of you didn't throw your hands in the air with confusion I might make a second installment about some more advanced topics.

  2. #2
    Join Date
    Jan 2007
    Location
    Kansas
    Posts
    3,760
    Mentioned
    1 Post(s)
    Quoted
    3 Post(s)

    Default

    Good tutorial, simple stuff, but fun stuff.


Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Intro to Flash
    By WhoCares357 in forum Computer Help and Tutorials
    Replies: 8
    Last Post: 12-01-2008, 12:06 PM
  2. stewie's intro
    By stewiemaniac in forum Who Are You ? Who ? Who ?
    Replies: 3
    Last Post: 10-14-2008, 08:48 PM
  3. Intro
    By RS Rebel in forum Who Are You ? Who ? Who ?
    Replies: 7
    Last Post: 07-05-2007, 12:02 AM
  4. intro whaaaat?
    By Poonage in forum Who Are You ? Who ? Who ?
    Replies: 0
    Last Post: 10-24-2006, 09:40 PM
  5. Syko Intro
    By Sykotik in forum Who Are You ? Who ? Who ?
    Replies: 4
    Last Post: 07-01-2006, 09:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •