views:

152

answers:

2

I need to know how to get something to work. I've got a class with a constructor and some constants initialized in the initializer list. What I want is to be able to create a different constructor that takes some extra params but still use the initializer list. Like so:

class TestClass
{
    const int cVal;
    int newX;
    TestClass(int x) : cVal(10)
    { newX = x + 1; }
    TestClass(int i, int j) : TestClass(i)
    { newX += j; }
}

Totally terrible example, but it gets the point across. Question is, how do I get this to work?

A: 

You can't do this in C++03, you'll have to retype the initializer list. This will be fixed in C++0x. Coincidentally, the syntax is exactly what you have, and even more coincidentally the example on Wikipedia is nearly your code. :)

Bruce
+4  A: 

There's no way for one constructor to delegate to another constructor of the same class. You can refactor common code into a static member function, but the latter cannot initialize fields, so you'll have to repeat field initializers in every constructor you have. If a particular field initializer has a complicated expression computing the value, you can refactor that into a static member function so it can be reused in all constructors.

This is a known inconvenience, and a way to delegate to another constructor will be provided in C++0x.

Pavel Minaev