What is benefits of constructor overloading in c++ -Real Time Example

(Last Updated On: February 25, 2019)

Benefits of constructor overloading in c++ interview question – We need to answer why constructor overloading is required in C++ program? and what are advantages of it? and also, with real time example from your project.

Answer: Benefits of constructor overloading in C++ is that, it gives the flexibility of creating multiple type of objects of a class by having more number of constructors in a class, called constructor overloading. In fact, it is similar to c++ function overloading that is also know as compile time polymorphism. Hence, if we want to construct an object in different way then we need constructor overloading in C++.

Real time example scenario of constructor overloading:

Lets consider a real time example of constructor overloading. We have a music database and we want to allow users to access song information on below two criteria.

  1. Default user – Get limited information ( e.g title, year and genre etc.) from music database.
  2. Premium user – Get Full information (e.g g title, year , genre, mood, and tempo etc.)

Below is a class “Music” that process song information on the basis of above criteria. We have 2 overloaded constructors in Music class. Empty constructor Music() will process music information for default (free) users while overloaded constructor with parameter Music(char* user) will process premium users.

Program Example with comments:

 

Output:

processing song information by default user

processing song information by premium user