views:

108

answers:

3

Hi, I'm relative new to C++ and my background is in Java. I have to port some code from Java to C++ and some doubts came up relative to the Object Java's class. So, if I want to port this:

void setInputParameter(String name, Object object) { ..... }

I believe I should use void* type or templates right? I don't know what's the "standard" procedure to accomplish it.

Thanks

+1  A: 

It depends what you want to do with object.

If you use a template, then any methods you call on object will be bound at compile time to objects type. This is type safe, and preferable, as any invalid use of the object will be flagged as compiler errors.

You could also pass a void * and cast it to the desired type, assuming you have some way of knowing what it should be. This is more dangerous and more susceptible to bugs in your code. You can make it a little safer by using dynamic_cast<> to enable run-time type checking.

ataylor
+1  A: 
Seth
A: 

I wouldn't recommend a void*, since it accepts not only a pointer to any object, but also a pointer to any primitive type. Remember that C++ doesn't have runtime type checking as Java does. If you pass the wrong thing, it'll be quite difficult to debug.

Consider again what kind of object your method should accept. It's very rare in C++ that you'd accept 'any' object. So these objects are in general related (usually sharing the same abstract base class) so that would be the best candidate for the parameter type.

Theoretically you could create an empty Object class and make any class inherit directly or indirectly from it, (in the past some early C++ libraries did that), but in modern C++ that's not considered a good design.

Fabio Ceconello