Google News
logo
Dart - Interview Questions
What is a constructor in Dart? How is it different from a regular function?
In Dart, a constructor is a special type of function that is used for creating and initializing objects of a class. It is called when you create a new instance (object) of a class using the `new` keyword or using constructor cascading.

Here are some key points about constructors in Dart and how they differ from regular functions:

1. Purpose : The primary purpose of a constructor is to initialize the state (data) of an object when it is created. It is responsible for setting the initial values of instance variables and performing any necessary setup operations.

2. Name : Constructors have the same name as the class they belong to. This allows Dart to associate the constructor with the class and determine which constructor to call when creating objects.

3. No return type : Constructors do not have an explicit return type specified. They implicitly return an instance of the class being constructed.

4. Execution : Constructors are automatically invoked when an object is created using the `new` keyword or constructor cascading. They are executed before any other code inside the class.

5. Overloading : Dart supports constructor overloading, which means you can define multiple constructors with different parameter lists. This allows you to create objects with different initializations or provide flexibility in object creation.

6. Default constructor : If you don't define any constructors in a class, Dart provides a default constructor. The default constructor does not take any parameters and initializes the object with default values (e.g., null for object references, 0 for integers, etc.).

7. Initialization list : Constructors can have an initialization list, which is a comma-separated list of expressions preceded by a colon (`:`). The initialization list allows you to set the initial values of instance variables before the constructor body executes.
Here's an example that demonstrates the concept of constructors :
class Person {
  String name;
  int age;

  // Constructor with parameters
  Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // Named constructor
  Person.guest() {
    name = 'Guest';
    age = 18;
  }
 
  // Constructor with initialization list
  Person.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];

  // Regular function
  void sayHello() {
    print('Hello, my name is $name. I am $age years old.');
  }
}

void main() {
  // Creating objects using different constructors
  Person person1 = Person('Alice', 25);
  Person person2 = Person.guest();
  Person person3 = Person.fromJson({'name': 'Bob', 'age': 30});

  // Calling a regular function
  person1.sayHello();
  person2.sayHello();
  person3.sayHello();
}​

In the above example, the `Person` class has multiple constructors. The first constructor takes `name` and `age` as parameters and initializes the instance variables. The second constructor named `guest` sets default values for a guest user. The third constructor `fromJson` takes a JSON map and initializes the object based on the provided data.

Regular functions, on the other hand, are not associated with a class and are standalone entities. They are defined using the `returnType functionName(parameters)` syntax and can be called anywhere in the code.

The key difference between constructors and regular functions is that constructors are used specifically for object initialization, while regular functions are used for general-purpose operations and logic that may or may not be related to object creation and initialization.
Advertisement