Make your own free website on Tripod.com
 
« May 2007 »
S M T W T F S
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
You are not logged in. Log in

Programming Tips
Monday, 21 May 2007
Calling a constructor from another constructor of the same class...
Mood:  a-ok
Topic: C++

Many times I had to write an init function to make initializations common for all constructors.

But now I 've found a way...

class MyClass
{
    public:
         MyClass()
         {
               cout << "Default constructor: " << m_nNumber << endl;
               m_nNumber = 20;
         }

         MyClass( int nSomeNumber_i ) :  m_nNumber( 10 )
         {
               // Call default constructor.
               ::new((void*)this)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
              new(( void* )this) MyClass( nOneNumber_i  );
              cout << "Constructor with two parameters: " << m_nNumber << endl;
         }

      private:
         int m_nNumber;
};// End MyClass

void main()
{
       MyClass mc( 10, 30 );
}


Posted by Nibu babu thomas at 11:06 AM
Updated: Monday, 21 May 2007 11:11 AM

Tuesday, 11 August 2009 - 1:44 PM

Name: "Oxzen Media"
Home Page: http://www.oxzenmedia.com/

great post...thanks for the tips. We will come back often. Thanks

View Latest Entries