Object-Oriented Programming is a way to integrate with objects which can contain data in the form (attributes or properties of objects), and code blocks in the form of procedures (methods, functions of objects). These attributes and methods are variables and functions that belong to the class, they are generally referred to as a class member. Constructors are one of the members of classes, if you are asking what is a constructor in C++ ? or How you can create a constructor in C++, How you can call constructors? Here below we answer all these;
The Constructor in C++ is a function, a method in the class, but it is a ‘special method’ that is automatically called when an object of a class is created. We don’t need to call this function. Whenever a new object of a class is created, the Constructor allows the class to initialize member variables or allocate storage. This is why the name Constructor is given to this special method.
Creating a Constructor in C++
To create a Constructor, we should use the same name of the class, followed by ( and ) parentheses as below,
Calling a Constructor in C++
To call this contractor just create a new object with this class, it will be automatically called. Like this below,
Constructor Example in C++
Here is the full code about defining a constructor and creating a new object;
Note that , the Constructor has always the same name as the class and it is always public
, and it does not have any return value, but a Constructor may have parameters.
Constructor with Parameters in C++
Constructors have no return value but may have parameters. In this example below we define a constructor to set name, age and height of any objects from THuman class,
Now we can create and construct worker1 object at the same time as below,
This is a good full example about The Constructor that creates and constructs two workers.
Constructor with Parameters Example in C++
Constructors has no return value but it may have parameters. In this example below we define a constructor to set name, age and height of any objects from THuman class,