4

I am trying to write an exception class convinient to use with a constructor behaved like printf, example:

class ExcBase
{
    ExcBase(const char *fmt, ...)
    {
        // call things like vsprintf
    }
};

but inheritance of construct does not seem available in c++, so I want write a inherited class like:

class ExcChild : public ExcBase
{
    ExcChild(const char *fmt, ...)
       : ExcBase(fmt, ...) // XXX: how to pass the trailing parameters to the constructor?
    {
    }
};

or I will have to write the same constructor for all the child classes, and that was too annoying...

this question troubles me a lot, and I can not figure out a way to solve this... any information will be a great help...

Tim
  • 257
  • 3
  • 9

4 Answers4

1

You can inherit constructors with the using clause if you don't need your code be compiled on old compilers that don't support it (and the upcoming VC++11 will be considered "old" this way, though...)

Or maybe you can put the actually construction work in a vprintf like function and let the constructor call it.

BlueWanderer
  • 2,671
  • 2
  • 21
  • 36
  • According to this: http://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport no compiler has inheriting ctors yet. Bummer. – emsr Apr 19 '12 at 03:28
  • c++11 standards proposed this, but is not implemented by gcc till now. – Tim Apr 19 '12 at 04:17
1

Don't try to do all the work in the constructor. Break it into pieces - provide a function that builds a string in whatever convenient fashion you want, and pass that string to the constructor.

std::string format_string(const char * fmt, ...);

class ExcBase
{
    ExcBase(const std::string & message);
};
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • +1, but be careful, I got my head bitten off for asking how to do such a thing: [see here](http://stackoverflow.com/questions/2880248/stdstring-resize-and-stdstring-length) – dreamlax Apr 19 '12 at 04:04
0

you could template it with a C++11 tuple - but that's the only thing I can think of.

Tobias Langner
  • 10,634
  • 6
  • 46
  • 76
  • Thanks! that's a great idea, but since I am writing a exception class, the inheritance relations are more important. – Tim Apr 19 '12 at 04:09
0

If you separate out the complicated work into a function that takes a va_list argument, you should be able to call that from each child constructor (which you'd still have to implement for each child type). Then your duplicated code (per class) would just be declaring va_list, then calling va_start, your new (base) function, and va_end. There's a post here on SO about doing that.

Community
  • 1
  • 1
Tanzelax
  • 5,406
  • 2
  • 25
  • 28
  • I am now solving this issue by a workround of defining a macro that declares the desired constructor -- since an exception class is not that huge -- and all the derived class explicitly invoke this macro. – Tim Apr 19 '12 at 04:12