tags:

views:

89

answers:

5

Let say I have a object. I'm assigning that to an integer.

MyClass obj1 = 100;//Not valid

Let's say, I have a parameterized constructor which accepts an integer.

MyClass(int Num)
{
    // .. do whatever..
}

MyClass obj1 = 100;//Now, its valid

Likewise on any circumstance, does the vice-versa becomes valid?!.

eg) int Number = obj1;//Is it VALID or can be made valid by some tweeks

EDIT:

I found this to be possible using Conversion Functions. Conversion functions are often called "cast operators" because they (along with constructors) are the functions called when a cast is used.

Conversion functions use the following syntax:

operator conversion-type-name ()

eg) Many have explained it neatly below

A: 

Yes, you need to add a conversion operator to MyClass

operator int();

Gary
+5  A: 

Yes, provided that the object is implicitly convertible to an int, either directly or through an intermediate object.

E.g. If your class have a conversion operator int it would work:

MyClass
{
public:
    operator int() const { return 200; }
};
Charles Bailey
+2  A: 

C++ constructors that have just one parameter automatically perform implicit type conversion. This is why conversion from int to MyClass works. To create conversion from MyClass to int you have to define operator int() inside MyClass.

Nikola Smiljanić
+2  A: 

Yes you can, using user defined conversions.

In your MyClass, define operator int()

So

class MyClass
{
 int myVal;

public:
operator int() { return myVal;}

}
Alan
A: 

MyClass is not an integer therefore you can't do int Number = obj1; You should have a method or operator(stated by others) in MyClass that returns an int. (int number = obj1.GetNum();)

PoweRoy