-2

I'm converting some old C-code into c++ and come across something strange, the C-code declared in .h file says: void Message(char *s, ...); and implementation head in .c

void Message(char *s, long x1, long x2, long x3, long x4, long x5, long x6, long x7, long x8, long x9, long x10){...}

When I make a 'straight' copy into a class declaration and implementation in c++ I get "prototype error".

Do I need to make a complete declaration as in the .c file oris there another way for c++ and class usage? The x1 ... x10 is option parameters and rarely used.

Working in linux with g++ and NetBeans 7.3

Anders S
  • 187
  • 11
  • 3
    You *do* know about default arguments in C++? If not then I suggest you [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about it. – Some programmer dude Feb 02 '17 at 09:58
  • 1
    see this http://stackoverflow.com/questions/1657883/variable-number-of-arguments-in-c – Groben Feb 02 '17 at 10:03
  • This C code just love its undefined behavior, doesn't it? – StoryTeller - Unslander Monica Feb 02 '17 at 10:04
  • 1
    That only "worked" (term used very loosely) in C because C doesn't encode parameter types as an implementation-dependent mangled name, and you used a left-to-right calling convention with caller-cleanup for parameters passed. C++ is much, *much* more strict about this. You can still use variable-arguments (see Groben's link), but can't do stuff like this and expect it to work (and honestly, you wouldn't want to in the first place). – WhozCraig Feb 02 '17 at 10:06
  • The ellipses does not really mean "optional". The function that implements `...` is supposed to use the `` facilities (`va_start`, `va_arg` etc.) to retrieve those trailing parameters. Even C++ has `...`, so there is a distinction between `...` and optional parameters. – PaulMcKenzie Feb 02 '17 at 10:19

1 Answers1

2

The C code shouldn't compile. To implement optional arguments in C++, put their values in the declaration:

void Message(char *s, long x1 = 0L, long x2 = 0L, long x3 = 0L, long x4 = 0L, long x5 = 0L,
        long x6 = 0L, long x7 = 0L, long x8 = 0L, long x9 = 0L, long x10 = 0L);

And then define your function like this:

void Message(char *s, long x1, long x2, long x3, long x4, long x5,
        long x6, long x7, long x8, long x9, long x10)
{
    // Function body
}

Note that you only need to specify the default values in one place. Do it in the declaration so that they're visible to clients.