1

Is it possible to type cast basic data type to class type by overloading conversion operator or do I have to overload = operator in c++

just to be clear

classname obj; float f=obj; 

is overloading typecasting operator from class to float and

float f; classname obj=f; 

is typecasting from float to class.So my question basically is for latter code to be correct is it possible by overloading typecasting or should I use overloading = operator.

I know overloading = works but I just wanted to know if it's possible to overload typecasting operator in that way.

1
  • That's implicit conversion. Casting is explicit conversion, like static_cast<float>(obj)or (classname) f. Commented Feb 28, 2020 at 6:51

2 Answers 2

1
classname obj; float f=obj; 

is possible if classname has an operator float(), for example

class classname { public: classname() : value(0.0f) {}; operator float() const {return value;}; private: float value; }; 

while

float f; classname obj=f; 

is possible if classname has a converting constructor, such as

class classname { public: classname(float v) : value(x) {}; private: float value; }; 

If you want to assign an existing object to a float such as

float x; classname f; f = x; 

requires an assignment operator.

class classname { public: classname() : value(0.0f) {}; classname &operator=(float v) {value = v; return *this;} private: float value; }; 

Obviously, if you want to construct or assign an object using a float, the class has to have both a relevant constructor AND a relevant assignment operator.

Sign up to request clarification or add additional context in comments.

2 Comments

So what I asked was that if we could explicitly cast float to classname
You may have thought you asked about explicit casting. Your post doesn't read that way to me. In any event, if a class supports an appropriate conversion constructor then an explicit cast using static_cast uses that. You could use another cast to force a conversion without such a constructor, but any use of the resultant object often lands you in the realm of undefined behaviour. Hence the common advice - don't use an explicit cast (C-style or C++ xxx_cast) unless you know exactly what the intended effect is. And, often, it is better to find an alternative.
1

classname obj=f; is initialization, then you can provide a converting constructor taking float to support constructing classname from float.

e.g.

class classname { public: classname(float) { ... } ... }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.