Search⌘ K

Constructors

Explore how to use constructors in C++ to create and initialize objects effectively. Understand the role of default constructors for automatic initialization and parameterized constructors for setting specific values during object creation. This lesson covers the syntax, purpose, and usage of constructors within classes to help you manage object instantiation.

In the previous lesson, we learned what classes and objects are.

Constructors are special methods for the instantiation of an object in the class.

It is declared inside the class but can be defined outside as well. The constructor:

  • has the exact same name as the class.

  • does not have a return type.

Default constructors #

Let’s revisit the Account class from the previous lesson:

class Account{
    public:
        Account(); // Constructor
        void deposit(double amt);
        void withdraw(double amt);
        double getBalance() const;
   
...