Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do casts call the constructor of the new type?

Tags:

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?

like image 952
Mankarse Avatar asked Jun 07 '11 05:06

Mankarse


People also ask

Is constructor called with new?

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 .

Who calls the default constructor?

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.

What is a constructor a class automatically called?

A constructor in C++ is a special method that is automatically called when an object of a class is created.

Why is constructor called only once?

By definition an object is only constructed once, hence the constructor is only called once.


1 Answers

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

like image 162
James Kanze Avatar answered Sep 20 '22 18:09

James Kanze