Reputation: 23
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
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
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
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
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
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