C++ – Classes and Objects, Part II

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

Constructors

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

cpp_class_constructor

cpp_class_constructor_2

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

cpp_class_constructor_defval

 

Constructors with Initialization Lists

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

cpp_class_constructor_initlist

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

Destructor

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.

cpp_class_constructor_destructorcpp_class_constructor_destructor_2

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.

 

 

 

Advertisements