C++ – Classes and Objects, Part II

Continuation of Lesson 9 in Sam’s Teach Yourself C++ in One Hour a Day, 8th Edition


A constructor is a special method that is run when an object is created. It lets the compiler know how the object will be built, or constructed. Constructors are useful for initializing member variables. You can also have multiple constructors, meaning they can be overloaded.

Basic syntax



The class parameters can also have default values, just like functions.



Constructors with Initialization Lists

Initialization lists are another way to initialize member variables. I think it looks cleaner than the previous method shown above.


The initialization value can be a parameter or a fixed value.


A destructor is automatically called when an object is destroyed — when it goes out of scope or when it is deleted via delete. Destructors cannot be overloaded.


Destructors are useful for resetting variables and releasing any dynamically allocated memory.


My next post will continue going over details dealing with classes and objects.


Note: Code screenshots were created using Polacode extension for Visual Studio Code.