Yeah but I don't need to know if the non-initialized another_node_types are null. |
Really? If you ever actually use these objects, then at some point, presumably you're going to need some way of telling whether your node contains a
nodes object or an
another_node_type object. How is that going to be determined?
I guess its not that big of a deal but I want to make my code "perfect". |
"Perfect" by what criteria? Robustness? Maintainability/readability? Optimal memory usage? Optimal performance? Conformance to some coding standard?
You can very rarely have all of these. If you try and make your code "perfect" with regard to one aspect, you usually wind up compromising it with regard to another. Personally, I would always value things like robustness and maintainability much higher than optimising memory usage - especially for something as paltry as storage for a single pointer.
I'm curious what you have in mind. Please post any code possible. I'm interested just for the sake of knowing another method thats OOP and possible using virtuals and inheritance/polymorphism. |
Well, polymorphism was one thing I was thinking of. In fact, I think that would be a better design. Simply have
nodes and
another_node_type inherit from a common base class, and store a single pointer to that base class..
But, understand, this will come with it's own memory overhead. If you want polymorphism, you'll need virtual methods, which means that vtables will be created for your classes, using memory.
Nevertheless, it would be a much better design for your code, eliminating the need for two pointers.
The other thing I was thinking of was the messy, old-school C solution of using a void* pointer, to store the address of whichever type of object is created. But if you ever want to use that data, your code will need to know how to interpret it, which means storing that information somewhere in the object, which means - you guessed it - memory usage.