Constructors

A constructor is a special type of class method that is always called when an object is instantiated.

 

Typically used to set initial values for an object.

 

A constructor has exactly the same name as the class but has no return type!

 

A constructor cannot be explicitly called. It is automatically called when an object is instantiated.

 

If no constructor is defined, the compiler will automatically provide one for you. This is similar to declaring to a primitive data type (e.g. an int or a char) whereby storage will be allocated but is not initialised.

 

The previous example now has a (inline) constructor included on line 11:

Compile & Run:

myTriangle width was set at 12
myTriangle height was set at 2000
myTriangle area: 12000
myTriangle width was set at 45.45
myTriangle height was set at 12.34
myTriangle area: 280.427

 

A new triangle instance called myDefault was declared on line 39. Notice that no values have been assigned and therefore the constructor has set the object's values to those specific in the class.

 

Here's the same code but with the constructor defined outside the class:

Compile & Run:

myTriangle width was set at 12
myTriangle height was set at 2000
myTriangle area: 12000
myTriangle width was set at 45.45
myTriangle height was set at 12.34
myTriangle area: 280.427

Leave a Reply