Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Constructor overloading and code reuse

Status
Not open for further replies.

chpicker

Programmer
Apr 10, 2001
1,316
Is there a way to overload a class constructor but still be able to reuse code? For instance, say I have two constructors for MyClass:
[tt]
MyClass::MyClass();
MyClass::MyClass(int a);
[tt]
I would like the second constructor to call the default constructor. If passed a parameter, it will do all of the same things the normal constructor does plus more code that is specific to the parameter.

Is there a way to do this, or am I stuck duplicating the code in both constructors?

Ian
 
Instead of calling one constructor from the other, you should call another function from both constructors for the things that are common to both:
Code:
MyClass::MyClass()
{
  CommonStuff();
}

MyClass::MyClass(int a)
{
  CommonStuff();

  m_iMyInteger = a;
}

void MyClass::CommonStuff(void)
{
  // do common things here
}
 
Ok, that makes sense. I assume, then, that it isn't possible to call the other constructor? I got some really weird errors when I tried, which made me think I just did it wrong.

Thanks!

Ian
 
MyClass::MyClass()
{
//do stg
}

MyClass::MyClass(int a):MyClass()
{
m_iMyInteger = a;
}

Read between the lines
 
Hmm...that didn't work. The compiler returns:

error C2614: 'MyClass' : illegal member initialization: 'MyClass' is not a base or member

Any other suggestions?

Ian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top