Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using void* as C++ equivalent of Java Object

I am trying to create a class, that contains a std::vector of void*. I have been told, that void* is the C++ equivalent to Object in Java. Since this is the C++ port of a program written in Java it should work in theory.

Java:

ArrayList<Object> list;

C++:

vector<void*> list;

This won't compile, giving the error: "'reference': illegal use of type 'void'".

Is void* really the C++ equivalent of Java's Object? Am i using it the wrong way?

like image 325
l'arbre Avatar asked Oct 25 '15 18:10

l'arbre


2 Answers

A Java Object is a fundamental base-class that provides some common properties to all Java classes.

There is no such thing in C++. If you want to design a polymorphic hierarchy, you design your own base-class MyBaseClass (abstract or not), and then design derived classes.

Thus, it's technically feasible to create a vector<void*> container, but it is meaningless. For proper software design, what you want is to design your base-class MyBaseClass, so that you will be able to create vector<MyBaseClass*> containers.

like image 174
Daniel Strul Avatar answered Sep 17 '22 09:09

Daniel Strul


A pointer to a void means that you have the memory address of something but you don't know what type that something is. You can create your vector with any kind of pointer, then when you add items to the vector you can cast your pointers to whatever pointer you used in the vector declaration. It's hokey but it will work syntactically. The down side is that you won't know what data items are in the vector.

like image 39
nicomp Avatar answered Sep 19 '22 09:09

nicomp