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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#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