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

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. The 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:
#include <iostream>
using namespace std;

class Music{
public:
/*constructor object to handle default users*/
Music(){
this->user =getDefaultUser();
//InitDefault(); // do some initialization for default user
}

/*constructor object to handle premium users*/
Music(char* user){
this->user = user;
//InitPremium(); // do some initialization for premium user
}

void querySong(){
cout<<"processing song information "<<"by "<< this->user <<"\n";
//other codes here
}
private:
char * user;
char *getDefaultUser(){
return "default user";
}
};

int main(){
/* Default user object to process songs with limited information*/
Music defaultUser ;
defaultUser.querySong();

/* Premium user object to process songs with full information*/
Music premiumUser("premium user") ;
premiumUser.querySong();

return 0;
}

Output:

processing song information by default user

processing song information by premium user

Related Posts