Home > C++, VC++ > Calling a constructor from another constructor of the same class…

Calling a constructor from another constructor of the same class…

Read this before reading further! It’s not a good practice to call constructor for initialization purpose, this entry is just for showing you that’s it’s possible to invoke a constructor.

#include
class MyClass
{
public:
MyClass()
{
cout < < "Default constructor: " << m_nNumber << endl; m_nNumber = 20; } MyClass( int nSomeNumber_i ) : m_nNumber( 10 ) { // Call default constructor, using placement new syntax. ::new((void*)this)MyClass; // Or this way, this one is much better, easy to understand this->MyClass::MyClass();

cout < < "Parametrized constructor: " << m_nNumber << endl; m_nNumber = 30; } MyClass( int nOneNumber_i, int nSecondNumber_i ) : m_nNumber( nOneNumber_i + nSecondNumber_i ) { // Call constructor with one parameter, using placement syntax new(( void* )this) MyClass( nOneNumber_i ); // Or this way, this one is much better, easy to understand this->MyClass::MyClass( nOneNumber_i );

cout << "Constructor with two parameters: " << m_nNumber << endl; } private: int m_nNumber; };// End MyClass void main() { MyClass mc( 10, 30 ); }[/sourcecode]

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: