1

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

5 Answers 5

6

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; }
};
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

Yes you can, using user defined conversions.

In your MyClass, define operator int()

So

class MyClass
{
 int myVal;

public:
operator int() { return myVal;}

}

Comments

0

Yes, you need to add a conversion operator to MyClass

operator int();

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.