Site icon Learn C++

Learn Constructors in C++ Classes

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 (methodsfunctions 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,

[crayon-661ecc47ceb00908206218/]

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,

[crayon-661ecc47ceb0a172105605/]

Constructor Example in C++

Here is the full code about defining a constructor and creating a new object;

[crayon-661ecc47ceb0d856240316/]

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,

[crayon-661ecc47ceb0e564368454/]

Now we can create and construct worker1 object at the same time as below,

[crayon-661ecc47ceb15531315439/]

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,

[crayon-661ecc47ceb17166053109/]

Get started building powerful apps with C++Builder!

Exit mobile version