3

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

dmessf
  • 1,025
  • 3
  • 11
  • 19
  • 2
    @Rui - i would say, the question is not clear. You want to port from Java to C++; but you have given the C++ code. What is that in Java you are trying to port.? Consider editing your question so that you get quick answers. – ring bearer Apr 15 '10 at 20:31
  • Also, C++ does not have a root Object class. Porting Java code to C++ is very far from trivial. –  Apr 15 '10 at 20:35
  • I know it doesn't have Object class, but I have to port it anyway. – dmessf Apr 15 '10 at 20:36
  • +1. I hope I'll never have to do something similar but I'm just curious how to 'replace' Object parameter in cpp. – Roman Apr 15 '10 at 20:40
  • @Rui There is no "standard" procedure, I'm afraid. You will have to re-design your Java code from scratch. –  Apr 15 '10 at 20:59

2 Answers2

2

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
  • 64,891
  • 24
  • 161
  • 189
1

If you want to accept a pointer to an arbitrary object, then you would want the type to be void *. However, that would be the end of the function, you can't do anything with a void * except store it's value or cast it to a pointer to some known object. If you're going to cast it anyway, then you probably know what the object is, so you don't need the void *.

C++ just doesn't have the same kinds of introspection abilities that Java has. In other words, there's not a convenient way to say something like myObject.getClass().getName(). The closest thing that I'm aware of is runtime type information (RTTI), which you can see in action here.

The other alternative is to create your own root class, and write your own introspection methods (a lot of C++ frameworks do this).

Seth
  • 45,033
  • 10
  • 85
  • 120