Static Cast

///////////////////////////////////////
// StaticCastDemo.cpp: demostrates static cast,including promotion constructor
// and cast operator
// Author: Yu Zhang
// Org: Syracuse University
// Contact: 315-314-0228
///////////////////////////////////////

/*
  Static Cast
---------------
toType toObject = static_cast<toType>(fromObject);

Creates toObject by calling promotion constructor from toType
  toType::toType(fromType fromObject);
or
  cast operator from fromType
 */

#include <iostream>
using namespace std;



class fromType; //forward declaration needed by toType constructor

class toType
{
public:
  inline toType(){cout<<"void constructor of toType is called \n";}
  //promotion constructor
   explicit toType(const fromType& fromObject); //keyword explicit declares this constructor to be non-converting,so that
                                         //avoid silent converting
  inline toType(const toType& toObject){cout<<"copy constructor of toType is called \n";}
};

// promotion constructor of toType
toType::toType(const fromType& fromObject)
{
  cout<<"promotion constructor of toType is called \n";
}

class fromType
{
public:
  fromType(){
    cout<<"void constructor of fromType is called \n";
  }
  operator toType();
};

//
fromType::operator toType(){
  cout<<"cast operator of fromType is called\n";
  return toType();
}





int main()
{
  fromType fromObject;//void constructor of fromType will be called
  toType toObject = static_cast<toType>(fromObject);//Precedency: promotion constructor of toType will be called if it
                                                  //is defined, if not, cast operator of fromType will be called
  toType toObject_another = fromObject; // only cast operator of fromType will be called
  //note: no copy constructor is called during casting
  return 0;
}

-------------------------------------------------------------------------
output:

void constructor of fromType is called
promotion constructor of toType is called
cast operator of fromType is called
void constructor of toType is called

-------------------------------------------------------------------------

if promotion constructor of toType is not implemented, say we commented the code part of it, then only cast operator of fromType will be called  .

output:

void constructor of fromType is called
cast operator of fromType is called
void constructor of toType is called
cast operator of fromType is called
void constructor of toType is called

Comments

Popular Posts