3

Can we cast an object with user-defined types, like we do for normal data types? Like say we do type cast for int like:

int variable_one = (int)variable_name;

So can we do like: (complex) object_name; where complex is the class I have written for complex number addition using operator+ overloading.

Is it possible in this normal way? Or do we need to write some function before calling this statment? Or is it not possible at all to type-cast like this?

3 Answers 3

9

int variable_one=(int)variable_name; is a C style cast.

C++ offers many casting operators:

  • dynamic_cast <new_type> (expression)
  • reinterpret_cast <new_type> (expression)
  • static_cast <new_type> (expression)
  • const_cast <new_type> (expression)

Have a look at article about type casting or refer to any C++ introductory book.

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

Comments

7

user defined type cast defined cast operator() for user type.

ex.)

#include <iostream> #include <cmath> using namespace std; struct Point { int x; int y; Point(int x, int y):x(x), y(y){} operator int(){ return sqrt(x*x+y*y); } }; int main() { Point point(10,10); int x = (int)point; cout << x ; } 

Comments

0

Why you want to do this? I guess you should write appropriate constructors if you want to create an object of your class. As you know, the constructors can be overloaded. So feel free to write more than one constructor if you need your objects to be constructed in different ways.

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.