2 answers
In object-oriented programming, a constructor is a special method that is called when an object is created from a class. The purpose of a constructor is to initialize the object's data members and perform any other setup that is required before the object can be used.
Was this answer helpful?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
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:
- The constructor must have exactly the same name as the class.
- It has no return type, not even
void. - It is called automatically when an object is created; it should be declared in the
publicsection so objects can be created. - 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?
Thanks for the feedback.
Sign up free to save answers and ask your own doubts
Your answer
Log in or create a free account to answer this question.