2

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Xavi
  • 57
  • 8
  • 6
    [Hint] You can try compiling the code to see what the compiler accepts. – NathanOliver Dec 20 '22 at 13:26
  • 2
    `Bar::Bar(int a=10,double b=7.10, char c='e')` is a default ctor so `Bar()` will work. – Jason Dec 20 '22 at 13:32
  • 1
    https://godbolt.org/z/KneWW11x5 – Alan Birtles Dec 20 '22 at 13:34
  • So if it was Bar b() instead will that be interpreted as a function? – Xavi Dec 20 '22 at 13:45
  • 1
    @Xavi Yes `Bar b();` declares a function due to [vexing parse](https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse). – Jason Dec 20 '22 at 13:45
  • thanks a lot all of you! – Xavi Dec 20 '22 at 13:49
  • 1
    `Bar b();` is simply a function declaration, just like `int f();`. This is **not** the [most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse); it comes from the same rule, and is occasionally confusing, but the most vexing parse it **always** vexing, which is why it's called that. – Pete Becker Dec 20 '22 at 14:26

1 Answers1

2

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

Jason
  • 36,170
  • 5
  • 26
  • 60