Home > Article > Backend Development > When Converting Between Types: Does the Source or Destination Object Take Precedence?
Conversion Constructor vs. Conversion Operator: Precedence
In C , both conversion constructors and conversion operators provide ways to convert objects between different types. When both are available for a given conversion, understanding their precedence is crucial to determine which will be called.
Precedence Establishment
The precedence between conversion constructors and conversion operators is defined by the C standard (13.3.1.4):
Overload resolution is used to select the user-defined conversion to be invoked. Candidate functions are selected as follows:
- Converting constructors (12.3.1) of the destination type are candidate functions.
- Conversion functions of the source type and its base classes that yield a type compatible with the destination type are candidate functions.
Operator Overriding Constructor
In the provided example code, where both a conversion constructor and a conversion operator are defined for class A to B, the conversion operator has precedence:
class A; class B { public: B(){} B(const A&) //conversion constructor { cout << "called B's conversion constructor" << endl; } }; class A { public: operator B() //conversion operator { cout << "called A's conversion operator" << endl; return B(); } };
This is because, when binding reference parameters (here, the implicit object parameter of the conversion function), the non-const reference in the conversion function (A&) has precedence over the const reference in the conversion constructor (const A&).
Object-Oriented Philosophical Considerations
Regarding the philosophical question of which class should be responsible for converting an object, the standard sides with the source class (A in this case). This aligns with the principle of encapsulation, as it allows the source class to control the conversion process and ensure the correctness of the resulting object (B).
It's ultimately up to the developer's discretion to determine the appropriate conversion mechanism for a specific scenario, considering factors such as encapsulation, abstraction, and code readability.
The above is the detailed content of When Converting Between Types: Does the Source or Destination Object Take Precedence?. For more information, please follow other related articles on the PHP Chinese website!