3

How can I enable explicit casting from, lets say int, to a user defined class Foo?

I made a conversion constructor from int to Foo, but is that it? I could overload a cast operator from Foo to int, but that is not what I'm looking for.

Is there a way to enable this piece of code?

int i = 5;
Foo foo = (Foo)i;
Shocky2
  • 504
  • 6
  • 24

3 Answers3

3

Something like this:

struct Foo {
    explicit Foo(int x) : s(x) { }
    int s;
};
int main() {
    int i = 5;
    Foo foo =(Foo)i;
}
Destructor
  • 14,123
  • 11
  • 61
  • 126
2

Read about converting constructor.

If you won't set constructor as explicit, it allows you to convert type (which constuctor accepts) to a (newly constructed) class instance.

Here is the example

#include <iostream>

template<typename T>
class Foo
{
private:
    T m_t;
public:
    Foo(T t) : m_t(t) {}
};

int main()
{
    int i = 0;
    Foo<int> intFoo = i;

    double d = 0.0;
    Foo<double> doubleFoo = d;
}
kocica
  • 6,412
  • 2
  • 14
  • 35
2

You need a constructor which accecpts an int

class Foo {

  public:
     Foo (int pInt) {
        ....
     }
     Foo (double pDouble) {
        ....
     }


int i = 5;
Foo foo(i);  // explicit constructors
Foo foo2(27);
Foo foo3(2.9);

Foo foo4 = i;  // implicit constructors
Foo foo5 = 27;
Foo foo6 = 2.1;
stefan bachert
  • 9,413
  • 4
  • 33
  • 40