Search

8.1 — Welcome to object-oriented programming

Back in lesson 1.3 -- A first look at variables, initialization, and assignment, we defined an object in C++ as, “a piece of memory that can be used to store values”. An object with a name is called a variable.

In traditional programming (what we’ve been doing prior to this point), programs are basically lists of instructions to the computer that define data (via objects) and then work with that data (via statements and functions). Data and the functions that work on that data are separate entities that are combined together to produce the desired result. Because of this separation, traditional programming often does not provide a very intuitive representation of reality. It’s up to the programmer to manage and connect the properties (variables) to the behaviors (functions) in an appropriate manner. This leads to code that looks like this:

So what is object-oriented programming? As with many things, it is perhaps understood most easily through use of an analogy. Take a look around you -- everywhere you look are objects: books and buildings and food and even you. Objects have two major components to them: 1) A list of relevant properties (e.g. weight, color, size, solidity, shape, etc…), and 2) Some number of behaviors that they can exhibit (e.g. being opened, making something else hot, etc…). These properties and behaviors are inseparable.

Object-oriented programming (OOP) provides us with the ability to create objects that tie together both properties and behaviors into a self-contained, reusable package. This leads to code that looks more like this:

This not only reads more clearly, it also makes it clearer who the subject is (you) and what behavior is being invoked (driving somewhere). Rather than being focused on writing functions, we’re focused on defining objects that have a well-defined set of behaviors. This is why the paradigm is called “object-oriented”.

This allows programs to be written in a more modular fashion, which makes them easier to write and understand, and also provides a higher degree of code-reusability. These objects also provide a more intuitive way to work with our data by allowing us to define how we interact with the objects, and how they interact with other objects.

Note that OOP doesn’t replace traditional programming methods. Rather, it gives you additional tools in your programming tool belt to manage complexity when needed.

Object-oriented programming also brings several other useful concepts to the table: inheritance, encapsulation, abstraction, and polymorphism (language designers have a philosophy: never use a small word where a big one will do). We will be covering all of these concepts in the upcoming tutorials over the next few chapters. It’s a lot of new material, but once you’ve been properly familiarized with OOP, you’ll likely never want to go back to pure traditional programming again.

Note that the term “object” is overloaded a bit, and this causes some amount of confusion. In traditional programming, an object is a piece of memory to store values. And that’s it. In object-oriented programming, an “object” implies that it is both an object in the traditional programming sense, and that it combines both properties and behaviors. From this point forward, when we use the term “object”, we’ll be referring to “objects” in the object-oriented sense.

8.2 -- Classes and class members
Index
7.x -- Chapter 7 comprehensive quiz

35 comments to 8.1 — Welcome to object-oriented programming

  • Sihoo

    Whoooah. Finally got past chapter seven and came to OOP. YAY!

  • gigawert

    "yoBack in lesson…" LOL

  • garryg

    Excellent! Clears up the muddied waters nicely. It seems that one needs to think in terms of Object-Oriented rather than just as an Object to be oriented. Think I get it.

    Garry

  • garryg

    Hi Alex- In this brief introduction to object-oriented-programming you talk about objects a lot but as far as I can tell you never really define what an object is. You may have done this in a previous chapter and, if so I apologize for my ignorance. FWIW ,In his ‘elementary’ textbook [Programming Principles and Practice Using C++] Bjarne Stroustrup defines an object as follows: "An object is a region of memory with a type that specifies what kind of information can be placed in it." This seems pretty straight-forward but the next sentence baffles me a bit. "A named object is called a variable." Does that mean that functions, which I believe(?) also occupy a place in memory, are not objects. If they are also objects what is(are) their datatype(s)? Second; should we then consider functions to be variables?
         Alex, you and Stroustrup write really cool (sometimes inscrutable to me) text. It’s really helpful
    to be able to cross-reference as well have this blog. Thanks
    Garry

    • Alex

      The term “object” is used in two different contexts. In the non-OOP sense, an object is as Stroustrup says. However, when we use the term object in an OOP sense, we mean something more: an object that combines both properties and behaviors. I rewrote this lesson a bit to try and make it clearer how OOP differs from traditional programming, and also how the term “object” is overloaded a bit.

  • Mike R.

    re: "…language designers have a philosophy: never use a small word where a big one will do)…"

    Instead, maybe:

    "…language designers have a philosophy: never use a big word where a diminutive one will do)…"

    :o)

    BTW: Great tutorial! Thanks!

  • Honorable sir i want to become a good programmer but my basic concepts are  to week in c plus plus .kindly guide me

  • abhay agarwal

    please reply thanks in advance
    <code>
    #include<iostream>
    #include<string.h>
    using namespace std;
    class human
    {
    public:
    string *name;
    int *age;
    public:
    human(string iname,int iage)
    {  name = new string;
      age = new int;
        *name = iname;
        *age= iage;
        cout<<"hello"<<endl;

    }
    void display()
    {

        cout<<"hi i am"<<*name<<"and i am"<<*age<<"years old"<<endl;
    }

    ~human()
    {
        cout<<"all memories are released "<<endl;
    }
    };
    int main()
    {
        human *anil=new human("anil",18);

        delete anil;
    anil->display();
    delete anil;
    delete anil;

        return 0;
    }</code>
    respected sir

    in this code I have declare object dynamicallyand nam and age variable also dynamically … do I need to use delete keyword in destructor for name and age… sice ihace use delete keyword for object in main function..

  • Jazz

    Alex, thank you once again! I’ve never read such a clear and good composed programing tutorial on english. I have one offtop question.

    Would you be so kind to tell me, what kind of C++ knowlege is more applicable for game design, and where to find simple game tasks for C++ newbie? For example, I want to write win32 application that will randomly generate 2D labirinth in console window.

    • Yaseen

      I too wanna know the answer…I am interested in game 2d game development 😀

    • Alex

      All of the content in these tutorials are potentially useful for game design. In addition, a good working knowledge of algorithms and data structures will help. You’ll also need to learn more about outputting (if you’re making a text-based game, maybe using the curses library -- if you’re making a graphical game, maybe using the SDL library).

      I’m not sure where you can go to find game tasks for newbies though.

      • Jazz

        Alex, I’ve found such tasks at CodinGame site (I hope you do not take it for advertising). My first sallary at game-dev position, will be yours 😉
        *cheers*

  • Yaseen

    Hi! Alex . I have a question that previous chapters from this chapter are for c or c++ ?

    • Alex

      C++, just building the foundations for object oriented programming (e.g. what is a function, what is a pointer, etc…)

      • Yaseen

        But Alex i wanna learn only simple C not C++ because first i wanna clear procedural programming lessons…

        • Alex

          If you really want to learn C, this is the wrong site. 🙂
          If you really want to learn procedural programming, you can do that with C++. Just start with chapter 0 and keep reading.

          There’s really no reason to learn C before C++.

  • Dear Alex, I’ll be very excited, If I understand the phrase "never use a small word where a big one will do"
    Would you mind give me a hint?

    • Alex

      Aspiring writers are often given the advice to “never use a long word where a short one will do”. In other words, favor short words instead of long ones, because short words are easier to read and understand.

      However, the C++ language designer seems to favor using lots of long words, like “inheritance, encapsulation, abstraction, and polymorphism”. So I was making a joke about this.

  • Andile

    Hey Alex, are you able to put up tasks for OOP? It would be of great help as it gets more confusing at this point.

  • Banelus

    I’d like to know how object oriented programming is associated with making some GUI applications. I found that there are some libraries that allows us to make GUI (like Qt, wxWidgets, WinAPI etc.). If some of these libraries are necessary, could you please recommend the one you find most easy/have the greatest potential?

    P.S.
    Sorry, but I didn’t know where to post it.

    • Alex

      There’s no direct relationship between object-oriented programming and GUI libraries (though some GUI library use OOP functionality and principles).

      Which GUI library to use is really outside the scope of this tutorial and my expertise. There are a ton of factors involved in picking the right one, including cost, whether you need cross-platform compatibility, etc…

  • Tim

    This might sound like a daft question but does everything in oop other than main() have to be an object (i.e. declared as a class) or is it ok to create objects where appropriate and just use ordinary functions when it is not really necessary to create an object.

    I have some code that creates and displays a popup message box which is extremely short lived (1 key press).  It seems a bit daft to put it in a class where I must declare a dynamic object then call a method and then delete the object rather than just call a function.  That said, I do not want to get into bad habits while I am learning.

    It doesn’t help that what I am working with is ncurses which is actually a c library.

    Thanks

    • Alex

      You can mix both traditional and object oriented programming. It’s totally okay to not use OOP for cases in which the added complexity isn’t warranted or necessary.

  • subramanyam

    Its very nice material..

  • Bruce

    I have been rather confused by some of the terminology of OOP, such as ‘class’, and ‘wrapper’, etc.; however, it appears as though these things are simply evolutions of the old ‘subroutine’ construct. Using a subroutine is now handled by the language which acts as a ‘traffic controller’ making it unnecessary for the programmer to keep up with ‘returns’ and allowing program flow to continue in any direction. If this is the case then it is not so hard to understand.

    • Jim

      Well, OOP provides another way of organizing not only code, but functions, in a way that is error proof while reusing. It also brings the concept of "members", so that people can organize information in packages, instead of variables.

  • Pathik

    So object oriented programming can only be done with C++…not java or anything other?

  • Hiu

    I’m thrilled after I read this article!! At this moment I’m taking intermediate C++ programming, and soon our teacher will teach us object-oriented programming (hope I’m right). And again, thank you for creating such a great C++ resource for programmers

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter