AUTO
AUTO

Reputation: 23

c++ class operator self-typecast

How can I create an operator function within a class that serves to typecast other types as an object of that class?

e.g.

class MyClass
{
  // ...
    // operator ??
  // ...
}

int main()
{
  MyClass obj;
  int Somevar;
  obj=(MyClass)Somevar; // class typecast
}

In general, is there an operator that allows this kind of typecast in exact syntax?

Upvotes: 2

Views: 861

Answers (5)

Konrad Rudolph
Konrad Rudolph

Reputation: 545548

Just add a constructor that takes one argument:

class MyClass {
    explicit MyClass(int x) { … }
};

called as:

MyClass x = static_cast<MyClass>(10); // or
MyClass y = MyClass(10); // or even
MyClass z(10);

This allows an explicit cast as in your example. (The C-style cast syntax is also supported but I won’t show it here because you should never use C-style casts. They are evil and unnecessary.)

Sometimes (but very rarely), an implicit cast is more appropriate (e.g. to convert from char* to std::string in assignments). In that case, remove the explicit qualifier in front of the constructor:

class MyClass {
   MyClass(int x) { … }
};

Now an implicit conversion from int is possible:

MyClass a = 10;

However, this is usually not a good idea because implicit conversions are non-intuitive and error-prone so you should normally mark the constructor as explicit.

Upvotes: 8

Errata
Errata

Reputation: 640

why not use operator=() ?

class MyClass
{
public:
  Myclass& operator=()(int i) {
  //do what you want
  return *this;
  }
}

int main()
{
  MyClass obj;
  int Somevar;
  obj = Somevar; // call operator=(somevar)
}

Upvotes: 0

cpx
cpx

Reputation: 17557

You need to construct the object implicitly.

class MyClass
{
int x;
public:
  MyClass(int X = 0):x(X){}  //also serves a default constructor
}

int main()
{
  MyClass obj = Somevar; // implicit type construction
}

Upvotes: 0

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

Define a constructor taking int argument.

But implicit conversions has some problems, so many that the language has the keyword explicit to prohibit them.

Mainly that's about overload resolution.

So, perhaps think twice before allowing the implicit conversion.

Cheers & hth.,

Upvotes: 1

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

Provide non-explicit constructor with argument of wanted type:

class MyClass {
public:
    MyClass( int x );
...
};

MyClass a = 42;

Note though: this is usually a bad idea.

Upvotes: 0

Related Questions