Course Object Oriented Programming

Constructors with Parameters

Course's Page 13 min Text by
User Image
Allan Garcia

Let us now look at the constructors with parameters. Let's start with a motivating problem.

Problem

When we define a single constructor, every object is initialized with the same values. However, in the real world, different objects can "be born" with different values in the attributes.

To understand it better, imagine the following analogy: when a person is born, they already have several specified characteristics (weight, height, age, eye colour, etc.).

Nevertheless, different people can be born with different characteristics, depending on the most different factors, such as genetics, the mother's diet and the most diverse organic processes that occur during pregnancy.

In programming, this type of factor, which influences a procedure, is specified as parameter.

Syntax

The creation of a constructor with parameters is very similar to what we saw in the last class. Thus, in the same way, one must create a constructor method, without the type of return and with the same name of the struct (or class) in question, passing, now, the parameters in parenthesis.

See an example:

struct classA {