Lesson 21 +10 XP

Objects and Variables

Objects and Variables

Before we write programs that do useful work, we need a way to store information. That's where objects and variables come in.

What is an object?

An object is a piece of memory (in your computer's RAM) that stores a value. You can think of it as a labeled box: the box has space inside, and what we put in the box is the value.

What is a variable?

A variable is an object that has a name we can use to refer to it. Naming the box makes it usable:

int x;   // creates an object named x that can hold an integer
  • The type (int) says what kind of value the box can hold.
  • The name (x) is how we talk about the box in our code.
  • The statement as a whole is a declaration: it tells the compiler "please create this variable".

Why store values?

Almost everything a program does works on data: a game tracks your score, a store keeps its prices, a chatbot remembers your name. Instead of re-typing a value again and again, we store it once in a variable and use the name everywhere.

int score = 10;
score = score + 1;   // add 1 to the stored score
cout << score;       // prints 11

The box starts holding 10, then we update it, then we print it. One name, reused all over the program.

A definition is a declaration

In everyday C++, "declaration" and "definition" are often used to mean the same thing: int x; creates the variable. A variable can be declared many times, but defined only once - the definition is the one that actually creates the box.

TL;DR

  • An object is a chunk of memory storing a value.
  • A variable is a named object: a type + a name.
  • int x; declares a variable named x of type int.
  • Variables let us store data once and reuse it anywhere in the program.