Two incomplete classes are shown below to illustrate the construction of an object of one class from an object of another.
[ 1] class bar
[ 2] {
[ 3] public:
[ 4] operator foo();
[ 5] };
[ 6]
[ 7] class foo
[ 8] {
[ 9] public:
[10] foo(bar b);
[11] };
[12]
[13] void f_of_foo(foo f);
[14]
[15] main()
[16] {
[17] bar b;
[18] f_of_foo(b);
[19] }
The function call on Line [18] requires converting the bar b to an object of class foo. There are two ways of doing this: using the constructor on Line [10], which provides a method for constructing a foo from a bar, or using the operator on Line [4] to produce an object foo from a bar object. However, the operator on Line [4] and the constructor on Line [10] cannot coexist because it is ambiguous which to use on Line [18].
In choosing between them, the following guidelines are suggested: favor the operator (Line [4]) because it has access to the internal attributes of class bar. This reduces the temptation to use friends and the need for access functions, which the constructor in class foo would need.
The constructor version is only necessary when an object is constructed from two or more parts. For example, water (H2O) is constructed from two instances of class hydrogen (H) and one instance of class oxygen (O). It is not possible for class hydrogen or class oxygen to provide an operator water() because an instance of class water is composed of both hydrogen and oxygen. Thus, class water should include the constructor
water::water(hydrogen h1, hydrogen h2, oxygen o);