C++ Constructors

A Constructor in C++ is always public and has the same name as the class name. Constructor gets called automatically when we create an object of a class. It does not have a return value. In this lesson, we will learn what are Constructors with examples and how to set parameters.

How to create a Constructor

In C++, to create a Constructor, the same class name is used followed by parentheses. Let’s say the class name is Studyopedia, therefore the Constructor would be the following:

Let us see an example to create a Constructor in C++:

Output

Constructor Parameters

Parameterized Constructor is a constructor with a particular number of parameters. This is useful if you have different objects and you want to provide different values.

First, let us see what a parameterized constructor looks like with 2 parameters:

Output

Now, let us understand the flow of parameterized constructors in the above program.

In the above code, we created 3 objects of the Rectangle class. As the parameters, we passed the length and width of the Rectangle to the parameterized constructor:

The length and width values pass to the parameterized constructor:

C++ Recursion
C++ Access Specifiers
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading