Home > Back-end >  Implicitly calling constructor
Implicitly calling constructor

Time:12-21

I have this exam question that says :

Bar can be properly constructed with ...

and I have to choose the 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 a function prototype, so it's out of the 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 this?

CodePudding user response:

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

  • Related