Search

1.3 — Introduction to objects and variables

Data

In lesson 1.1 -- Statements and the structure of a program, you learned that the majority of instructions in a program are statements, and that statements are grouped into functions. These statements perform actions that (hopefully) generate whatever result the program was designed to produce.

But how do programs actually produce results? They do so by manipulating (reading, changing, and writing) data. In computing, data is any information that can be moved, processed, or stored by a computer.

Key insight

Programs are collections of instructions that manipulate data to produce a desired result.

A program can acquire data to work with in many ways: from a file or database, over a network, from the user providing input on a keyboard, or from the programmer putting data directly into the source code of the program itself. In the “Hello world” program from the aforementioned lesson, the text “Hello world!” was inserted directly into the source code of the program, providing data for the program to use. The program then manipulates this data by sending it to the monitor to be displayed.

Data on a computer is typically stored in a format that is efficient for storage or processing (and is thus not human readable). Thus, when the “Hello World” program is compiled, the text “Hello world!” is converted into a more efficient format for the program to use (binary, which we’ll discuss in a future lesson).

Objects and variables

All computers have memory, called RAM (short for random access memory), that is available for your programs to use. You can think of RAM as a series of numbered mailboxes that can each be used to hold a piece of data while the program is running. A single piece of data, stored in memory somewhere, is called a value.

In some older programming languages (like Apple Basic), you could directly access these mailboxes (a statement could say something like go get the value stored in mailbox number 7532).

In C++, direct memory access is not allowed. Instead, we access memory indirectly through an object. An object is a region of storage (usually memory) that has a value and other associated properties (that we’ll cover in future lessons). How the compiler and operating system work to assign memory to objects is beyond the scope of this lesson. But the key point here is that rather than say go get the value stored in mailbox number 7532, we can say, go get the value stored by this object. This means we can focus on using objects to store and retrieve values, and not have to worry about where in memory they’re actually being placed.

Objects can be named or unnamed (anonymous). A named object is called a variable, and the name of the object is called an identifier. In our programs, most of the objects we create and use will be variables.

Author's note

In general programming, the term object typically refers to a variable, data structure in memory, or function. In C++, the term object has a narrower definition that excludes functions.

Variable instantiation

In order to create a variable, we use a special kind of declaration statement called a definition (we’ll clarify the difference between a declaration and definition later).

Here’s an example of defining a variable named x:

At compile time, when the compiler sees this statement, it makes a note to itself that we are defining a variable, giving it the name x, and that it is of type int (more on types in a moment). From that point forward (with some limitations that we’ll talk about in a future lesson), whenever the compiler sees the identifier x, it will know that we’re referencing this variable.

When the program is run (called runtime), the variable will be instantiated. Instantiation is a fancy word that means the object will be created and assigned a memory address. Variables must be instantiated before they can be used to store values. For the sake of example, let’s say that variable x is instantiated at memory location 140. Whenever the program then uses variable x, it will access the value in memory location 140. An instantiated object is sometimes also called an instance.

Data types

So far, we’ve covered that variables are a named region of storage that can store a data value (how exactly data is stored is a topic for a future lesson). A data type (more commonly just called a type) tells the compiler what type of value (e.g. a number, a letter, text, etc…) the variable will store.

In the above example, our variable x was given type int, which means variable x will represent an integer value. An integer is a number that can be written without a fractional component, such as 4, 27, 0, -2, or -12. For short, we can say that x is an integer variable.

In C++, the type of a variable must be known at compile-time (when the program is compiled), and that type can not be changed without recompiling the program. This means an integer variable can only hold integer values. If you want to store some other kind of value, you’ll need to use a different variable.

Integers are just one of many types that C++ supports out of the box. For illustrative purposes, here’s another example of defining a variable using data type double:

C++ also allows you to create your own user-defined types. This is something we’ll do a lot of in future lessons, and it’s part of what makes C++ powerful.

For these introductory chapters, we’ll stick with integer variables because they are conceptually simple, but we’ll explore many of the other types C++ has to offer soon.

Defining multiple variables

It is possible to define multiple variables of the same type in a single statement by separating the names with a comma. The following 2 snippets of code are effectively the same:

is the same as:

When defining multiple variables this way, there are two common mistakes that new programmers tend to make (neither serious, since the compiler will catch these and ask you to fix them):

The first mistake is giving each variable a type when defining variables in sequence.

The second mistake is to try to define variables of different types in the same statement, which is not allowed. Variables of different types must be defined in separate statements.

Best practice

Although the language allows you to do so, avoid defining multiple variables in a single statement (even if they are the same type). Instead, define each variable in a separate statement (and then use a single-line comment to document what it is used for).

Summary

In C++, we use variables to access memory. Variables have an identifier, a type, and a value (and some other attributes that aren’t relevant here). A variable’s type is used to determine how the value in memory should be interpreted.

In the next lesson, we’ll look at how to give values to our variables and how to actually use them.

Quiz time

Question #1

What is data?

Show Solution

Question #2

What is a value?

Show Solution

Question #3

What is a variable?

Show Solution

Question #4

What is an identifier?

Show Solution

Question #5

What is a type?

Show Solution

Question #6

What is an integer?

Show Solution


1.4 -- Variable assignment and initialization
Index
1.2 -- Comments

429 comments to 1.3 — Introduction to objects and variables

  • OTAKU

    will u cover the keywords in future lessons ? because for as a noob trying to learn C++ i think it's hard for me to learn all the keywords and when/how to use them
    Thnaks !!

  • Manuel Calzadillas

    Good lesson, I want to use c++ to see if I can make web application with HTML to help my father in his business..
    Hope to finish this tutorial soon

  • The test answers are often a little different than the paragraphs that talk about the subject. It might be nice if the definition that the test is looking for is either highlighted or the first definition of the item to be tested later.
    example: question 1 answer: What is Data?
       Data is any sequence of symbols (numbers, letters, etc…) that can be interpreted to mean something.
    paragraph definition: In computing, data is:
       any information that can be moved, processed, or stored by a computer.

  • wenom

    Great tutorial site. Thanks so much for evertything..

  • Shareware

    In this article/chapter, you mention "When an object is defined, the compiler automatically determines where the object will be placed in memory."

    But the compiler has nothing to do with memory, it only creates object files. What did you mean by that sentence?

    • Alex

      Good question. When the program is compiled, the compiler creates all the code that handles how each function will be called, and how/where function parameters, local variables, and other bits of data will be allocated and destroyed. Because the compiler can't know the specific memory addresses that objects will use (as that happens at runtime), it will typically generate relative addresses (e.g. the first function parameter might be defined to be at memory address 0, the second at memory address 4, etc...). These offsets are "converted" to real memory address at runtime, and may be different each time the function is called.

      Because this gets a bit complicated and it's not really relevant to the point of the lesson, I've updated the lesson to hand-wave over the details a bit more.

  • ops

    "Instantiation is a fancy word that means the object will be created and assigned a memory address. "

    Isn't "object creation" actually "assigning a memory address"? If yes, then your sentence sounds like they're different things ( created and assigned a memory address). Maybe it's overthinking, but just want to be sure.

  • Mark T Okedoyin

    A variable is like a building in the memory which we store numbers or characters or even nothing inside. We can furthermore manipulate or change these values. A program manipulates data to get desired result. The Identifier(name) of the variable is like the house address in the programm(Identifier) or in memory(memory address) while data type is like what kind of people can live in the house (Mexican, African, Chinese). Dont try to put an African man inside a Chinese man's home(a string inside an integer).

  • Vishal

    code

    #include <iostream>

    int main(int l)
    {
        int vae01;
        //variable basic dec.style.
        int vae02, vae03, vae04, vae05;
        //create same type of multiple variable seprated with camma.

    //    int var01, int var02;
        //wrong way to dec. a variable.
        int var03, var04;
        //correct.

    //    int vae1, double vae2;
        //wrong.
        int vae3;double vae4;
        //correct but not recomended;

        int vaw;
        double vaw01;
        //correct.

        //but try to define deffrent variable in seprate line.
        //like this...
        int _01;
        int _02;
        int _03;
        double _01D;
        double _02D;
        double _03D;
        char _01C;
        char _02C;
        char _03C;
        //this is recomended way to dec. a variable.
        //hope it's helpful.
        //THANK YOu.
        //Norule Games Company.

        
        
        
        
        
        
    //                           Learning from basics again    
    //...............................................................................................
        int i = 0;
        while (i < l) {
            std::cout << "Hello World by Norule studio!\n" << std::endl;
            std::cin.get();
            i++;

        };
        return 0;

    }

    /code

  • PinkFlower

    >>When an object is defined, the compiler automatically determines where the object will be placed in memory.

    >>When the program is run (called runtime), the variable will be instantiated. Instantiation is a fancy word that means the object will be created and assigned a memory address.

    What are the differences between those two statements? I mean I still can't figure it out if the compiler determines the address or it will be determined in the run time.

    • tsua

      The difference here is the concept of "instantiation". When the code is compiled the compiler assigns a spot in memory for the object. When the code is being executed (runtime) then an instance of the object is created and is placed in the memory address.

    • seaque

      the first sentence is creating room for object, the second sentence gives a memory address to object. When an object is defined, you create a house. When the program is run, the house will have a number.

  • sexy

    you said a address will be assiged at run time. but when i compile my renesas mcu c code. all variables in ram, the addresses already decided in map file....

Leave a Comment

Put all code inside code tags: [code]your code here[/code]