Reputation: 1471
Lets say i have a class
Class rofl {
int a;
float b;
rofl::rofl(int a, float b) {
this->a = a; this->b = b;
}
}
is it possible to do
rofl* sup = new rofl(5, 2.0f);
float hello = sup;
so that variable hello would get the value of sup.b?
Upvotes: 1
Views: 117
Reputation: 3471
No, in the case that you stated this is not possible. In your code, sup
is not a rofl
but a rofl*
, and creating a rofl*
to float
conversion is not allowed. Moreover, your question is ill-formed: sup.b
does not refer to anything.
That said, you probably don't need to dynamically allocate the instance, in which case the other answers are correct.
Upvotes: 1
Reputation: 272467
Yes, you can overload type-conversion operators:
class Rofl {
public:
operator float() const { return b; }
...
};
See http://ideone.com/Y7UwV for a demo.
However, see Item 5 of Scott Meyers' More Effective C++, entitled "Be wary of user-defined conversion operations". Allowing implicit conversions to-and-from complex types can often lead to all sorts of subtle typo bugs.
Upvotes: 8
Reputation: 97565
You can also go the other way around:
class rofl {
public:
float operator=(float f) { b = f; return f; }
...
};
rofl sup(5, 2.0f);
sup = 4.0f;
demo, based on @Oli's answer
Upvotes: 1