Skip to main content
gamedev.net
🔒 Locked

va_argument and base class object pointers

Started by mooreaa 2 replies 700+ views
Original Post
mooreaa
mooreaa
Hello, I am having a problem with va_lists

struct param
{
	union{
		int i;
		float f;
		...
		BaseObj* ptr
	};
	TYPEID type;
};

param myfunc(const char* types, ...)
{
	TYPEID type = parse_type(types);

	va_list	arguments;
	va_start( arguments, types );
		
	param arg;

	switch(type)
	{
	...
	case TYPE_BASE_OBJECT:
		arg.type = TYPE_BASE_OBJECT;
		arg.ptr = va_arg ( arguments, BaseObj* );
	}
	va_end ( arguments );
	
	return arg;
}


this is a simplified example of what I am trying to do... unfortunately the arg.pObj when inspected later doesn't seem to be functioning correctly... the parameters are all garbage If I, instead, manually create my param with the following function it works as expected:

param addObject(std::string varname, BaseObj* pObj)
{
	param arg;
	arg.data.pObj = pObj;
	arg.type_id = TYPE_BASE_OBJECT;
	
	return arg;
}


I am not sure why the va_arg method is causing the program to get messed up. as I am only passing a pointer i don't see why it would be a problem to retrieve the pointer... Any help would be appreciated.
Sandman
Sandman
What exactly are you trying to achieve here?

It looks to me like you're trying to implement a very longwinded, overcomplicated and potentially bug-ridden mechanism for loading values into some kind of generic container, in which case you're better off scrapping it altogether and just setting the values of param directly.

va_lists are pretty hacky and evil things, and you can forget about type safety. Do you really need to be using them here?
Evil Steve
Evil Steve
If you pass in a pointer to a derived class to a va_arg function, the pointer passed in is the pointer to the derived class. If you need to pass a pointer to the base class, cast it before passing it to the variadic function (E.g.: MyFunc("blah", (BaseObj*)pDerived);).

Yet another reason not to use variadic functions.
swiftcoder
swiftcoder
Quote:
Original post by Sandman
va_lists are pretty hacky and evil things, and you can forget about type safety. Do you really need to be using them here?


Everything he says, but also you may want to look into "operator chaining" instead (as used by std::streams and boost::format).
Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.