...

/

Constructors

Constructors

Learn about constructors and how to declare, overload, and call them.

Introduction

Constructors are special member functions of a class that are automatically called when an object of the class is declared.

  • A constructor is a member function that is usually public.

  • A constructor can be used to initialize member variables when an object is created.

A constructor’s name must be the same as the name of the class it is declared in. A constructor cannot return a value. So, no return type, not even void can be used while declaring a constructor. If no constructor is declared, C++ will generate a default constructor that initializes data members to default values.

Declaration and initialization

Constructors are mostly public. We can declare and initialize the constructor within the class or declare ...