user3234
user3234

Reputation: 13

A class object to another datatype?

Can you convert a class object to for example to int, double, char etc.. is it called implicit or explicit conversion?

class MyClass
{
int x;
};

int main()
{
    MyClass MyObject; //convert my object to int
}

Upvotes: 1

Views: 230

Answers (2)

John Gordon
John Gordon

Reputation: 2704

A constructor can also function as a cast operator going the other way.

class Foo {
public:
    Foo(const Bar &)   // Bar -> Foo
};

class Bar {
public:
    Bar(const Foo &)
};

Upvotes: 0

Erik
Erik

Reputation: 91260

Create a casting operator:

class Foo {
public:
    operator int() const { return 1; }
};

class Bar {
public:
    operator Foo() const { return Foo(); }
};


int main() {
    Foo f;
    Bar b;
    int i1 = f; // implicit, just one conversion
    int i2 = b; // not valid
    int i3 =  static_cast<Foo>(b); // Convert b to Foo explicitly, Foo to int implicitly
}

Upvotes: 1

Related Questions