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 );
}