Akaanthan Ccoder
Akaanthan Ccoder

Reputation: 2179

Can I assign a object to a integer variable?

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

Upvotes: 1

Views: 280

Answers (5)

RvdK
RvdK

Reputation: 19790

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();)

Upvotes: 0

Alan
Alan

Reputation: 46813

Yes you can, using user defined conversions.

In your MyClass, define operator int()

So

class MyClass
{
 int myVal;

public:
operator int() { return myVal;}

}

Upvotes: 2

Nikola Smiljanić
Nikola Smiljanić

Reputation: 26873

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.

Upvotes: 2

CB Bailey
CB Bailey

Reputation: 791799

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; }
};

Upvotes: 6

Gary
Gary

Reputation: 5732

Yes, you need to add a conversion operator to MyClass

operator int();

Upvotes: 0

Related Questions