Make your own free website on Tripod.com
 
« July 2017 »
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
Friday, 18 May 2007
Invoking constructor of a constructed class!!
Mood:  bright
Topic: C++

class MyClass
{

   public:

      MyClass()
      {
           cout << "Previous value: " << m_nNum << endl;
           m_nNum = 20;
      }

   private:
      int m_nNum;
};

void main()
{
     // Constructor invoked once here
     MyClass mc;

     // Now we are going to invoke once more
    ::new(( void* )&mc) MyClass;

     // First time printed number will be garbage, second time number will be 20
}


Posted by Nibu babu thomas at 3:26 PM
Updated: Monday, 21 May 2007 11:22 AM

Newer | Latest | Older