Skip to main content
gamedev.net
🔒 Locked

Prevent Implicit Typecast (C++)

Started by Kustaz 4 replies 1.3k views
Original Post
Kustaz
Kustaz
Ok, lets say I have 2 classes; A and B. A is at heart, B, but more specialised. I Can convert an A to a B, And can multiply an A by a B. However, I cant multiply an A by an A. But, since an A can be converted to a B, a typecast is implicitly applied, and an incorrect result is achieved! how can I prevent this implicit typecast from occuring? Thanks in advance.
Nitage
Nitage
By what mechanism is A being converted to B?
Kustaz
Kustaz
A typecast operator, for example:

operator B(A arg_)
{
return arg_.Data;
}
Nitage
Nitage
Remove that operator and replace it with an explicit constructor in B:
class B{...public:    explicit B(A arg_)        :data_(arg.Data)    {    }...};


The c'tor allows conversion from A to B, but because it's marked explicit it won't implicitly convert.
Kustaz
Kustaz
Thanks Nitage, you've been very helpful, i now have my code working.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.