I have a class CS which is to represent the co-ordinate system in 3D i.e.(x, y, z)
class CS
{
private:
double x;
double y;
double z;
}
CS::CS()
{
x = NULL;//this causes x = 0//i want the address of x to be 0x000000 & not x = 0
y = NULL;
z = NULL:
}
I want that the user can create a CS (0, 0, 0). In the constructor i want to initialise the address of x, y & z to NULL. this is to differentiate between the user defined (0, 0, 0) & the default value. I am creating the objects of CS dynamically, so there is no point in using the following code:
class CS
{
private:
double *x;
double *y;
double *z;
}
CS:CS()
{
x = new double;
x = NULL;
//same for y & z
}
Primarily, i want to manually assign 0x000000 address to any variable(int or double or char) without using pointers. any suggestions?
You have several options:
double
, a not-a-number is often a natural candidate. Forint
andchar
it's often more tricky to pick a good value.None of these options is indisputably better than the other two as they involve different tradeoffs. Take your pick.
One way to get the semantics of what you want would be to have the datatype of the coordinates be a type that carries with it a value indicating whether it has been assigned. Something like this.
I'd prefer something like this over cuter methods unless memory is really scarce for some reason.
If the coordinates are either all default or all set, then you can have a single flag rather than a coordinate datatype that includes the flag.
That's not what you want. What you want is the ability to detect whether a variable has been set or not.
Others have suggested things like using a specific floating-point value to detect the uninitialized state, but I suggest employing Boost.Optional. Consider:
boost::optional
either stores the type you give to the template parameter or it stores nothing. You can test the difference with a simple boolean test:The downside is that accessing the data is a bit more complex:
Why can't you simply do this:
If I understand correctly, you want to be able to tell the difference between an invalid, default constructed CS and a valid one with values
(0.0, 0.0, 0.0)
. This is exactly whatboost::optional
http://www.boost.org/doc/libs/1_47_0/libs/optional/doc/html/index.html is for.This is the problem. Firstly, default value? What default value? Why should there be a default value? That's wrong. And secondly, it's fundamentally impossible for you to change the address of any variable.
What you want cannot be done and even if it could, it would be a horrendously bad idea.