In C++, a constructor is a specific procedure that is called automatically when a class object is formed.
A constructor is a specific sort of class member function that initialises the class’s objects. When an object (instance of a class) is created in C++, it is immediately invoke. Because it has no return type, it is a unique member function of the class.
In object-oriented programming, a constructor is a particular method of a class or structure that initializes a newly formed object of that kind. The constructor is automatically invoke whenever an object is created.
It is similar to an instance method in that it can be use to set the values of an object’s members to default or user-defined values. It normally has the same name as the class. A cons, however, is not a legitimate method because it does not have a return type, despite its resemblance. It initialise the object rather than performing a task by running code, and it cannot be static, final, abstract, or synchronised.
Example:
class NewClass { // The class
public: // Access specifier
NewClass() { // Constructor
cout << “This is a Blog!”;
}
};
int main() {
NewClass myObj; // Create an object of NewClass (this will call the constructor)
return 0;
}
Types of constructor
- Default
- Copy
- Parameterized
Interested in learning about similar topics? Here are a few hand-picked blogs for you!
- What is computer processor?
- Describe recursion?
- What is OSI model?
- Phenomena of cryptography?
- What is machine learning?