user3384414 user3384414 - 1 year ago 82
C++ Question

Pass variable argument list to base constructor in C++

Is it possible in C++ to pass a variable argument lists to a base constructor?

I could just copy the code of the base constructor to the derived class, an handle the variable argument list there, but that would lead to unwanted code duplication.

This is what I tried so far:

class A{
A(const char * fmt,...){
va_list ap;
va_start( ap, fmt );

class B: public A{
B(const char * fmt,...):A(fmt){;};

int main(){

But the constructor doesn't pass the variable arguments to the base class constructor.

Answer Source

Just use variadic templates (and drop this C-style stuff):

struct A {
     template<typename ... Args>
     A(const char * fmt, Args&& ... args) {
          printf(fmt,std::forward<Args>(args) ...);

struct B: public A {
  template<typename ... Args>
  B(const char * fmt, Args&& ... args) : A(fmt, std::forward<Args>(args) ...) {}


B("Print %d and %s",1,"hello");  //prints "Print 1 and hello"


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download