Object Oriented Programming(OOP) Series: Constructor and Destructor

Object Oriented Programming(OOP) Series: Constructor and Destructor

Constructor and Destructor in simple terms with illustrations

In this series as promised earlier we'll be brushing up OOP concepts in the most simplest form with examples in PHP, Javascript and Dart.

So far in this series we've covered Classes & Objects , Attributes & Methods.

A Class can be a parent of many objects while an object is a child of a class. Inside the class closure{} variables are called attributes(data members) and the functions inside that get or set values are called methods.

Next let's look at constructors and destructors

Constructor

An object or something that is used to design another object or build an object is called a constructor.

Basically in simple terms it’s responsible to design and describe what the class expects from or is passing to its object upon creation or access and also it can be seen as a method that is automatically invoked and executed when an object is created from a class. It’s a unique member function in a class responsible for initializing the expected parameters or behavior of its objects upon creation (instantiation).

The idea of it been unique is that it can take the name of the class. For example if we’ve a constructor in the Car class it can be called upon to get the information of a car objects upon creation because every car should have an information. The constructor will automatically construct the attributes (data members) of a Car for the new object (Toyota).

A constructor is solely responsible for initiating the object for behavior, specifically instantiating initial values for all its attributes in the class.

Note: arguments are parameters passed into a function or method or in our case a constructor.

Types of Constructor:

Default constructor: a constructor that accepts no arguments into the class or object.

Parameterized constructor: constructor that accepts arguments for manipulation or evaluation of data members and methods.

Copy constructor: there are scenarios where we need to adjust the constructor of a class we can do this by referencing the class of the constructor as it’s argument or parameter.

Overloaded constructor: occurs when there are multiple things to automatically execute in a class automatically by defining multiple constructors.

The constructor method is defined to ease the process of initializing the data attributes within a class. Note: constructors are optional in a class and some object oriented languages can automatically create one for you when there is none.

Destructor

A destructor is a unique method that is invoked to destroy or unset a constructor after it’s been called automatically to construct something for its class or object. So if we call a constructor to accept the information of a car as arguments we will need to unset the objects when the constructor is destroyed for memory optimization and performance issues. In some languages it’s preceded by ~ or __

A destructor can also be referred to as clean up.

Destructors de-initialize class objects when they are destroyed. Destructors execute behind the scenes when the objects are destroyed by the built in Garbage Collection facility. Destructors are also optional and does not accept arguments or return a value. We can have only one destructor defined in a class.

In the next part of this series we'll be looking at Access Modifiers.

**Please note: The examples below are used to illustrate the concepts and not to define their full meaning in the languages. **

Simple illustration in Javascript

class Car{
    constructor(type, model) {
        this.type = type;
        this.model = model;
    }
}

let toyota = new Car("Toyota", "Camry");

console.log(toyota);

//output is Car {type: "Toyota", model: "Camry"}

class Car{
    constructor() {
     console.log('Default constructor');
    }
}

let toyota = new Car();

//out put is Default constructor

constructor(type, model) is a parameterized constructor because it accept two arguments.

let toyota = new Car("Toyota", "Camry"); while creating an object for the Car class it expects two values(one for type and the other for model) as seen in this code.

**example of default constructor **

constructor() { console.log('Default constructor');

}

Destructuring in Javscript is quite different from the approach of OOP.

const toyota= { year: '2018', model: 'C1' };

const {year, model} = toyota;

console.log(year); // 2018 console.log(model); // C1

Simple illustration in Dart:

class Car{
Car();
}

//this class constructor has no arguments and is referred to as default constructor
class Car{
  String model;
  Car(this.model);

  Car.make(this.model);

  Car.fromCompany(Car another) :
    color = another.color,
    name = another.name;

Car.empty(); //will u
}

void main(){
  var toyota = new Car('Toyota Camry'); //accessing the Car parameterized constructor 
}

Car(this.model); //this class constructor accepts one argument and is referred to as parameterized constructor

Car.make(this.model); is an example of a named constructor it allows for overloaded constructor(defining multiple constructor)

Car.fromCompany(Car another) //the car constructor is referenced in another constructor

The main() method is a constructor in Dart that's automatically executes the code inside it's closure.

Dart is a garbage-collected language, so any object that you don't hold any references to will eventually be garbage collected and freed by the runtime system.

Simple illustration in PHP

In PHP, there are two ways we can write a constructor method inside a class.

**create a method with the name __construct() inside the class. **

create a method naming exactly the same as class name. Using our Car class for example we can create a constructor by using the name Car().

<?php 

class Car
{
    private string $name;

//Parameterized constructor Before PHP 8 
    public function __construct(string $name): void
    {
        $this->name = $name;
    }

//Parameterized constructor in PHP 8
    public function __construct(private string $name){}

//Default constructor 
    public function __construct()
    {
      return 'default constructor';
    }

/**
A destructor is called when the object is destructed or the script is stopped or exited.
PHP will automatically call the __destruct method at the end of this script.
**/
    public function __destruct(){

  }

}

?>

Stay tune for the next article on the OOP Series: Access Modifiers

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!