Reputation: 65
I was going through a book called Programming Principles and Practices using C++ but found a strange behavior of class construction. Suppose I have a class as follows:
class Foo {
public:
Foo(int x)
: y { x } { }
private:
int y;
};
and I have another class which has an instance of class Foo as its member object
class Bar {
public:
Bar(Foo x)
: y { x } { }
private:
Foo y;
};
When I do the following:
int main()
{
Bar obj_1 { Foo { 1 } };
Bar obj_2 { 2021 }; // this doesn't give me error?
return 0;
}
obj_1 was constructed as specified in the constructor, but obj_2 doesn't give me any error message and to me it seems it just magically works. My intention of having a member of a class as an instance of another class was to force the constructor to take a class instance as its argument, but not an integer.
Why doesn't it give me incorrect type error?
Upvotes: 1
Views: 45
Reputation: 117876
You can prevent this implicit conversion by declaring the Foo
constructor explicit
explicit Foo(int x) : y { x } { }
in main
this would require the caller to change their obj_2
instantiation to
Bar obj_2 { Foo{2021} };
Upvotes: 1