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

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

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy