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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calling a constructor from a different constructor 1

Status
Not open for further replies.

KaiDaniel

Programmer
Jun 4, 2002
7
DE
Hi! My problem is the following. I'd like to call a constructor from within a different constructor to prevent code duplication.
E.g. the first constructor sets the first attribute and another constructor sets a second attribute and then calls the first constructor to set the first one, too.

Code:
Test::Test(int a)
{
  this->a = a;
}

Test::Test(int a, int b)
{
  this->b = b;
  Test::Test(a);  // this does not work 
}

In Java you can just call
Code:
Test(a);
If you do the same in C++ it just defines a new object of the class Test.

Is there a way of doing this in C++?
Thanks in advance for an answer.
KaiDaniel.
 
i dont think you can do what you want in C++
:0)
try taking common code out to a different function, that will be additionally called in your various constructors
 
Do it in the initializer list of the constructor.

Example:

Test::Test(int a, int b) : Test(a)
{
//Code goes here
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top