What are the rules to determine whether or not a particular static_cast will call a class's constructor? How about c style/functional style casts?
Constructor functions or, briefly, constructors, are regular functions, but there's a common agreement to name them with capital letter first. Constructor functions should only be called using new .
It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
A constructor in C++ is a special method that is automatically called when an object of a class is created.
By definition an object is only constructed once, hence the constructor is only called once.
Any time a new object is created, a constructor is called. A static_cast
always results in a new, temporary object (but see comment by James McNellis) either immediately, or through a call to a user defined conversion. (But in order to have an object of the desired type to return, the user defined conversion operator will have to call a constructor.)
When the target is a class type, C style casts and functional style casts with a single argument are, by definition, the same as a static_cast
. If the functional style cast has zero or more than one argument, then it will call the constructor immediately; user defined conversion operators are not considered in this case. (And one could question the choice of calling this a "type conversion".)
For the record, a case where a user defined conversion operator might be called:
class A { int m_value; public A( int initialValue ) : m_value( initialValue ) {} }; class B { int m_value; public: B( int initialValue ) : m_value( initialValue ) {} operator A() const { return A( m_value ); } }; void f( A const& arg ); B someB; f( static_cast<A>( arg ) );
In this particular case, the cast is unnecessary, and the conversion will be made implicitly in its absence. But in all cases: implicit conversion, static_cast
, C style cast ((A) someB
) or functional style cast (A( someB )
), B::operator A()
will be called.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With