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.
- Default user – Get limited information ( e.g title, year and genre etc.) from music database.
- 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:
using namespace std;
/*constructor object to handle default users*/
//InitDefault(); // do some initialization for default user
/*constructor object to handle premium users*/
this->user = user;
//InitPremium(); // do some initialization for premium user
cout<<"processing song information "<<"by "<< this->user <<"\n";
//other codes here
char * user;
return "default user";
/* Default user object to process songs with limited information*/
Music defaultUser ;
/* Premium user object to process songs with full information*/
Music premiumUser("premium user") ;
processing song information by default user
processing song information by premium user