Skip to content
doubtly

2 answers

Answer: A constructor is a special member function of a class that has the same name as the class and is called automatically when an object is created, to initialise the object's data members.

Syntax (C++):

class ClassName
{
  public:
    ClassName()          // constructor
    {
        // initialise data members
    }
};

Example:

class Student
{
    int roll;
  public:
    Student()            // default constructor
    {
        roll = 0;
    }
};

Student s;   // constructor called automatically, roll = 0

Rules for defining a constructor:

  1. The constructor must have exactly the same name as the class.
  2. It has no return type, not even void.
  3. It is called automatically when an object is created; it should be declared in the public section so objects can be created.
  4. It can take arguments (parameterised constructor) and can be overloaded, but it cannot be virtual (C++) and is not inherited.

Any two of these rules are enough for the answer; rules 1 and 2 are the most important. The same rules apply in Java, where the syntax is ClassName() { ... } inside the class.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.