1

I have a class definition like this:

class Paint{
 AnyType* Color;
};

what I want to do is to create a class (AnyType) whose object can be assigned any object of any class type. like so:

class Blue{}; 
class Green {};`

Paint MyPaint;
MyPaint.Color = new Green();
// color gets changed
MyPaint.Color = new Blue();

how do I declare AnyType?

Class AnyType{
//class definition
};
  • 1
    So you want a `void*`? – NathanOliver Dec 17 '15 at 19:16
  • 1
    The answer to the question literally as asked is `void*` but it does not seem that the question correctly identified the requirement. Instead, I think you really wanted `Green` and `Blue` to be derived from some common base type. – JSF Dec 17 '15 at 19:18
  • @JSF agree. I just was not sure if they just want color objects or any object possible. – NathanOliver Dec 17 '15 at 19:19

3 Answers3

3
class Paint{
 BaseColor* Color;
};

class BaseColor {}

class Blue : BaseColor {}; 
class Green : BaseColor {};`

Paint MyPaint;
MyPaint.Color = new Green();
// color gets changed
MyPaint.Color = new Blue();
Riad Baghbanli
  • 3,105
  • 1
  • 12
  • 20
1

The pure C++ standard way to do this, would be to reinterpret_cast back and forth from a void*. This will, however, require you to know the correct type to cast back from later on.

If you are open to 3rd party solutions, this is one such application for boost::any.

That being said, there are very few times when something like this is a good idea. There are often better designs to solve your problem. Frankly when someone wants to do something like this it is an XY problem and their actual problem can be solved in a more robust way.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

Your Color member should probably be of some ColorType type. And classes Green and Blue should be derived from ColorType.

Please see rbaghbanli's code which does exactly this (accepted answer).

Then you can put all aspects shared by classes Green and Blue into ColorType, which is quite useful.

If you user a void* or boost::any there is nothing you can really do with this pointer, as C++ forgets what it is actually pointing to.

Background: C++ is completely statically typed and does not allow introspection. The only available runtime mechanism is virtual functions, and this mechanism is quite limited.

If you really need something which can be any type, you have to write it yourself. But I assume you do not really need this. I assume you need Can be any of a kind. and this is well enough supported in C++ through derivation.

Johannes Overmann
  • 4,914
  • 22
  • 38