user396404
user396404

Reputation: 2819

C++ pointers to different types

Let's say I have a function in C++ that can return either a pointer to either an int, string, or double. What would be the return type for this function?

I would also like a variable that can store that return value once the function returns it. Should I just use the same type for that?

Upvotes: 0

Views: 2681

Answers (2)

shengy
shengy

Reputation: 9749

One way is the void* way which is demonstrated in Philipp's answer

Another way is to encapsulate your type in a object which derives from some common base object(i.e. Object in Java, QObject in Qt), and let your function return the common base object.

QObject obj = foo();

Check the library you are using, maybe there are some existing common base classes you can use.

Btw, I think template functions is also a good way to solve your problem.

Upvotes: 3

Philipp Claßen
Philipp Claßen

Reputation: 43950

The only match is void*.

 void* pResult = foo();

To use the value later, you will have to cast to int*, string* or double*. So you need to keep track of the actual type in some way.

Upvotes: 3

Related Questions