Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implicitly calling constructor

I have this exam question that says :
Bar can be properly constructed with and I gotta choose correct option(s)

class Bar{
public:
Bar(std::string);
Bar(int a=10,double b=7.10, char c='e');
};




a) Bar{4,2,6};

b) Bar{"xyz",2};

c) Bar(true,false);

d) Bar{5,"abc"};

e) Bar();

I think that it can certainly be constructed with a) (implicit conversion from int to char) , I also think that it should not be possible to construct with b) and d) because there is no implicit conversion from const char* to double. I think that Bar() is function prototype so it’s out of question. Then c) true and false can be converted to int and double. So my thoughts are : a) and d) can construct Bar properly.
Am I right, can someone with more experience confirm? Thank you very much

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think that Bar() is function prototype so it’s out of question.

No, Bar::Bar(int =10,double =7.10, char ='e') declares a default constructor, so Bar() is completely valid and will use the above default ctor.

Similarly, Bar{4,2,6}; and Bar(true, false) will also use the default ctor.

class Bar{
public:
Bar(std::string){}
Bar(int a=10,double b=7.10, char c='e'){
    std::cout <<"default " << std::endl; 
}
};
int main()
{
    Bar(true, false); //uses default ctor
    Bar();           //uses default ctor see demo link below
    Bar{1,2,3};      //uses default ctor

}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading