Can I initialise a value in a parameterised constructor in C++ -


i have program in giving error. not able undertsand reason. please elaborate

#include<iostream> using namespace std;  class room {     int length;     int width;  public:     room()     {         length=0;         width=0;     }     room(int value=8)     {         length=width=8;     }     void display()     {         cout<<length<<' '<<width;     } };  main() {     room objroom1;     objroom1.display(); } 

the error call of overloaded function room() ambiguous.

the call of constructor in declaration

room objroom1; 

is indeed ambiguous because your class has 2 default constructors.

according c++ standard (12.1 constructors)

4 default constructor class x constructor of class x can called without argument.

so constructor

room() {     length=0;     width=0; } 

is default constructor. , constructor

room(int value=8) {     length=width=8; } 

also default constructor because can called without argument.

moreover there logical inconsistance because when first constructor called data members length , width initialized 0 while when second constructor called without argument data members initialized 8.

and second constructor not use parameter!:)

simply define second constructor following way

room( int value ) {     length = width = value; } 

and better declare data members having unsigned integer type. example

unsigned int length; unsigned int width; 

also better if function display have qualifier const. example

void display() const {     cout<<length<<' '<<width; } 

because not change class data members.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -