More flexible parameter passing in C++

Laurent Pointal laurent.pointal at laposte.net
Tue Jan 1 13:14:59 EST 2002


[posted and mailed]

hungjunglu at yahoo.com (Hung Jung Lu) wrote in 
news:8ef9bea6.0112311125.559ff28d at posting.google.com:

> Hi,
> 
> This is a question on C++. I guess I am too spoiled with Python
> features. Now it's hard for me to do things in C++. :)
> 
> Consider the case of hook methods. You have parent classes that
> declare hooks. Well, a parent class may not do much with a hook, but
> the child class may do something with it. That's what hooks are for.
> 
> Now, the parent class does not know nor does it care what's on the
> parameter list. Python can handle all this well: the parameter list
> can be quite dynamic in Python. There are many ways to handle dynamic
> parameter lists.
> 
> But I am having hard time with C++, now.
> 
> One way out is to use hashmaps (equivalent to Python dictionaries),
> but this is bad for performance.
> 
> Is there some object-oriented way of making parameter passing more
> flexible in C++? I mean, the goal is avoid modifying the header
> declaration of methods... especially in situations where you have
> subclasses and sub-subclasses.

You may have posted to comp.lang.c++ (or comp.lang.c++.moderated)... I set 
followup-to to this newsgroup.

But as I'm replying...

First solution:
===============
You can do it a la printf, see variable number of arguments in your C++ 
documentation (the ellipsis at the end of functions prototype) and look for 
va_list, va_start, va_arg, va_end.

But:
-Its far from type safe.
-Its far from object oriented.
-I dont think we can call it a pattern.

Second solution:
================
In C++, you can have multiple methods with same name but with different 
argument types (ex. multiple constructors with different parameters). 
So you can have a base foo method, with the arguments known by your base 
class, and a foo method in your subclass, with your own arguments - you can 
call base class foo by giving right arguments. 

Its type safe, its true C++.

But:
-Its not a variable number of arguments.
-The compiler must know what method to call, so you may have to coerce 
arguments from time to time to correspond to the method stamp you want to 
call.
-The programmer can call your parent foo method simply by giving the right 
arguments, and there may be risks he does this without knowing that he dont 
call your foo method.
-There is no direct relation from your sublass' foo and the parent class' 
foo.


Conclusion: Mapping Python code to C++ code is not immediate :-)


> Hung Jung

A+

Laurent.



More information about the Python-list mailing list