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; 
3
  • The constructor should't be explicit. Explicit constructor prevents implicit conversion! Commented Aug 27, 2017 at 16:40
  • foo isn't a type, while Foo is a type Commented Aug 28, 2017 at 19:47
  • @stefanbachert a typo, thank you! Commented Aug 29, 2017 at 21:17

3 Answers 3

3

Something like this:

struct Foo { explicit Foo(int x) : s(x) { } int s; }; int main() { int i = 5; Foo foo =(Foo)i; } 
Sign up to request clarification or add additional context in comments.

1 Comment

@Shocky2 Why? The OP is asking for code which would enable a C-style cast, which will of course work just fine with an explicit ctor.
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; } 

Comments

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; 

3 Comments

Assign Foo* to Foo ? Dont think so
Ups, to much java
Non-explicit constructor*

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.