...

/

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 created.

  • 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 it inside the class and write the method outside the class.

A constructor​ for the DayofYear class can be declared as follows:

Press + to interact
class DayOfYear {
public:
DayOfYear() // Constructor
{
// Body of constructor
}
private:
int month;
int day;
};

Unlike normal member functions of a class, a constructor can’t be called by using . operator or -> operator. Constructors are automatically called when we create an ...