Alex Rivera | Logout

When do casts call the constructor of the new type?

Asked 2011-06-07T05:36:24.047
25

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?

Edit
Report

1 Answer

17

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>( someB ) );

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.)

answered 2011-06-07T07:51:10.600

Your Answer