Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ calling superclass constructor with va_arg

I have a base class, which includes a constructor with variable argument list:

class Super {
public:
    Super(int num, ...);
...
}

Now, in my subclass constructor I need to somehow call this superclass constructor, but how do I do it? The usual thing, naturally, doesn't work:

class Sub {
public:
    Sub(int num, ...) : Super(???) { ... }
...
}

So what do I put into instead of ???

I do have another constructor that accepts a vector, but having one like this is a direct requirement from the client.

like image 252
Aleks G Avatar asked Jul 06 '15 12:07

Aleks G


1 Answers

As with any variable function, always provide a list version, too:

void foo(int a, ...) { va_list ap; va_start(ap, a); vfoo(a, ap); va_end(ap); }

void vfoo(int a, va_list ap) { /* actual implementation */ }

Same here:

#include <cstdarg>

struct Super
{
    Super(int num, ...) : Super(num, (va_start(ap_, num), ap_)) { va_end(ap_); }
    Super(int num, va_list ap);

private:
    va_list ap_;
};

Your derived classes would perform the same vapacking gymnastics and then use the list form of the super constructor.

If having a data member just for the purpose of construction upsets you and your class is otherwise copyable or movable, you can also forgo the variable constructor and instead have a named, static member function that does the pack wrapping.

like image 153
Kerrek SB Avatar answered Oct 27 '22 00:10

Kerrek SB