Custom Typecasts

Hey there,
I'm interested to know how this c++ code works internally:

1
2
3
4
5
(int)32
// or..
(char)32
// or..
(float)32

I'm interested in this typecasting operation because,
I want to know if I can do something like this:

CustomType ctVar = (CustomType)32;

Would I have to create a class, then somehow overload an operator
to achieve this functionality?

Thanks for your time.
This would work if CustomType is a class type with a non-explicit constructor taking an integer as argument.
1
2
3
4
5
6
7
class CustomType
{
public:
	CustomType(int);
private:
	/* private members */
};
What do you mean by non-explicit constructor?

Do I still have to implement the constructor?
If not, how does the class know how to interpret the int data?
Non-explicit meaning the explicit keyword was not applied to the constructor.

Yes, you have to implement the constructor.

http://coliru.stacked-crooked.com/a/d215d573a169c799
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

struct MyClass
{
    MyClass(int x)
    {
        std::cout << "x = " << x << std::endl;
    }
};

int main()
{
    MyClass a = 1;
    MyClass b (2);
    MyClass c {3};
    MyClass (4);
    MyClass {5};
    (MyClass)6;
    static_cast<MyClass>(7);
}












x = 1
x = 2
x = 3
x = 4
x = 5
x = 6
x = 7
See also: http://coliru.stacked-crooked.com/a/4537930929bd67b1
Last edited on
Okay cool,
Thank you very much.
Topic archived. No new replies allowed.