Start learning free

LESSON 276 OF 667 · FUNCTIONS & CLASSES

Creating Objects in C++

Lesson

TL ; DR:

  • An object is an instance of a class — a real, usable copy made from the blueprint.


  • In C++, you create an object on the stack just by declaring it. No new keyword needed:

    Dog rex;
    

  • Each declaration creates a separate object, even if they all come from the same class.



Full lesson:

In the previous lesson you defined the Dog class — the blueprint. But a blueprint isn't a dog. To get an actual dog you can interact with, you need to create an instance of the class. An instance is also called an object.


Stack-allocated objects

The simplest way to create an object in C++ is to declare it just like a regular variable:

Dog rex;

This creates a Dog object on the stack, named rex. Notice there's no new keyword — that's specific to C# / Java / JavaScript style. In C++, plain variable-style declaration creates the object directly.


Many objects from one class

You can declare as many Dog objects as you want, and each one is independent:

Dog rex;
Dog buddy;
Dog luna;

rex, buddy, and luna are all Dog objects, but they're different objects living at different stack addresses. Modifying one won't affect the others.


Heap allocation (advanced — not used here)

C++ does also have new, but it allocates on the heap and gives you a pointer that you have to delete later:

Dog* rex = new Dog();
// ...later:
delete rex;

Don't use this style for these lessons — stack objects are simpler and don't require manual cleanup.


Your task

The Dog class is already defined for you. Below it, declare three Dog objects named rex, buddy, and luna. The pre-filled validation will print one line per dog you've successfully created:

rex exists
buddy exists
luna exists
STEP 1 OF 3
    Ctrl + Enter to check