12.1 — Welcome to object-oriented programming

Back in lesson 1.3 -- Introduction to objects and variables, 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 short word where a long 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 and it clicks, you may 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.

12.2 -- Classes and class members
11.x -- Chapter 11 comprehensive quiz

71 comments to 12.1 — Welcome to object-oriented programming

  • Ged

    Just wanted to thank you for this awesome tutorial. And ask a few questions? Is there anything else that you would suggest learning before starting OOP that you didn't mention in the previous chapters?

    Btw Found a funny story and thought I could share with you about a game dev that didn't know what for/while loop was, neither array, structs and a lot of other things. But he managed to create the game (the length of the code is crazy).
    Here is the code -
    Here is the game that he created -

    So basically this says that if you know what an "int", "bool" and "if" is, you can do anything :D

  • Lord Voldemort

    what does it mean- "never use a small word where a big one will do".

  • Hello, I want to thank you for what you guys have done, this website is really something wonderful. I wanted to ask you if you could tell me what websites or books could you recommend me for learning data structures in cpp (linked lists, queue, binary trees, etc.)?. I really want to take this next step but don't know the best resources to do so. I apologize for posting this comment in this section, but I didn't know how else to ask (sent e-mail already but didn't get a response).

    Thank you very much.

  • Darshan

    Generally speaking, is it correct to say that everything inside a function is either a keyword or an object (of course excluding parenthesis)? Is an entity which is not a keyword an object (atleast upto this point)?

  • Erik

    Hello Alex, thanks for a great tutorial.

    Regarding C++ and OOP, would you say it is viable when deploying on embedded systems, where performance constraints are a much more real concern than for PC development?

    • Alex

      Viable, definitely. The best choice? Not sure. I haven't worked in that industry and can't speak the particulars of that industry.

  • NXPY

    Is OOP only beneficial for the programmer ? I believe it does not enhance memory or processing considering we are only organising functions and data into objects.

    • Alex

      You might think so at first, but consider some of the benefits of OOP: higher productivity, better maintainability, and higher quality code. While that's good for developers, that's just as good for customers. It means they get programs sooner, cheaper, and at higher quality than they might otherwise.

      OOP programs may user more memory or run more slowly, but often the difference isn't substantive. And in cases where it is, some of the development time that was saved by using OOP can be invested in optimizing for performance.

  • Lan

    I encountered a problem at the 28th line

    Thank you !!

  • Rommel Villon

    Great learning site.
    Wish you all the best in life and may you have tons of patience updating, answering comments, guiding and keeping this place you created.

  • ray

    whats funny is. im completely new to programming ( less than a week) . nevermind c++ ( main interest are game design/hack ) anyway. i got up to using classes/objects/constructors with thenewboston series before coming here, so they entire time i was reading and doing quizzes i was thinking how much easier most of this would be with creating separate classes for these programs lol.

  • Peter Baum

    Nice explanation for this chapter but there was one tiny phrase I didn't like: "once you’ve been properly familiarized with OOP, you’ll likely never want to go back to pure traditional programming again."  I think that is misleading.  OOP is perfect for some things and completely inappropriate for others.  I don't think you have to over sell OOP at this point.  The advantages will be obvious soon enough. :)

  • Val

    Hello Alex, I wrote a few thoughts regarding the difference between traditional (procedural) and object-oriented programming.
    Could you please look and tell me if I understand this difference correctly? Sorry if it's too naively.

    • Alex

      Sounds generally correct to me!

      Object oriented programming is a bit of a mental shift from traditional function-oriented programming, but once you get the hang of it it's hard to go back!

  • nik

    Hello! Great tutorial! Do you plan on adding lessons about OOP design in general(how to design good classes and relationship among them)? That would be nice I guess.)Or if you don't contemplate that, can you suggest some good books,articles on this topic?

  • Shamlei

    Hey Nice lessons !

    Still feel like I'm kinda weak when it comes to understanding pointers and references, I know the stuff but it's not natural I would sometime use a value instead of a reference for example for a swap function and realize after it wouldn't work.

    How can I make it stick in my head clearly ? I can finish most of the exercices on my own but when coding I'm not 100% sure of what I'm doing and sometimes there's trial and error involved, especially when references are involved.

    Great website, keep up the great work !

    • Alex

      It's hard to answer this question since pointers and references are used in multiple context. Is your question focused around when to use pointers and references in the context of passing values to functions?

      • Shamlei

        I don't exactly understand what happens when a variable is passed to a function that takes in references, like in the swap function.

        What happens to the variable ? Does the function creates references automatically ?

        I know when to use what, it's more like I don't know what exactly happens or why I would use it.

        • Alex

          Nothing happens to the variable argument. It stays as it is. When the function is called, the reference parameter is created, and set to reference the argument. Then, within the function, the reference parameter can be used as if it were the original argument. At the end of the function, the reference is destroyed, but the original argument remains. Note that because the reference is treated as if it were the original argument, any changes to the referenced value change the argument!

          So basically, you should pass by reference when you:
          * Want to have the function be able to modify the value of the argument
          * Are passing a non-fundamental type, to avoid making a needless copy (for fundamental types, this doesn't matter since making a copy is cheap)

  • 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.


  • 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

    • 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)..."


    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
    using namespace std;
    class human
    string *name;
    int *age;
    human(string iname,int iage)
    {  name = new string;
      age = new int;
        *name = iname;
        *age= iage;

    void display()

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

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

        delete anil;
    delete anil;
    delete anil;

        return 0;
    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 :D

    • 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 ;)

  • 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++.

        • Prasetya

          I've learned java and now I want to implement the whole java standard library with c++, not all, just api level 1(android). But I can't figure out how to implement this OOP thing:



          I've already asked on internet and most answer is to forward declare a class like:

          But when I try, I keep getting "invalid use of incomplete type 'class B'" error.
          Is it because of my compiler or what? Please help

          • nascardriver

            You need to forward declare `String` in "Object.h"

            This allows you to use `String` references and pointers, but you can't use any members of `String` and you can't use `String` by value.

  • 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?

    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.


    • 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 all code inside code tags: [code]your code here[/code]