Tag Info

Hot answers tagged

80

From my perspective: your design is wrong. Translated to natural language, you are saying the following: Given we have animals, there are cats and fish. animals have properties, which are common to cats and fish. But that's not enough: there are some properties, which differentiate cat from fish, therefore you need to subclass. Now you have the problem, ...


74

It is... Not great. I've worked with code that did this clever trick and it led to confusion. After all, you would expect to be able to just assign the BigObject into a SmallObject variable if the objects are related enough to cast them. It doesn't work though - you get compiler errors if you try since as far as the type system is concerned, they're ...


29

C++ casts are more restrictive (so express your intent better and make code review easier, etc.). They're also much easier to search for, if you ever need to.


25

It doesn't always make sense to add functions to the base class, as suggested in some of the other answers. Adding too many special case functions can result in binding otherwise unrelated components together. For example I might have an Animal class, with Cat and Dog components. If I want to be able to print them, or show them in the GUI it might be ...


24

First, understand that those lines are not equivalent. int* anInt = (int*)aFloat; // is equivalent to int* anInt = reinterpret_cast<int*>(aFloat); What is happening here is that the programmer is asking the compiler to do whatever it can to make the cast. The difference is important because using static_cast will only ask for a base type that is ...


18

In a weakly-typed language, type-casting exists to remove ambiguity in typed operations, when otherwise the compiler/interpreter would use order or other rules to make an assumption of which operation to use. Normally I would say PHP follows this pattern, but of the cases I've checked, PHP has behaved counter-intuitively in each. Here are those cases, ...


12

Option C: a "C++-style" cast, because it is indistinguishable from a construction: int anInt = int(aFloat); or even: int anInt(aFloat); That aside, other than these trivial cases with primitives, which are well understood, I prefer to use x_cast<>s over C-style casts. There are three reasons why: They more narrowly define the operation the ...


11

The problem is the line byte q1 = keyboard.nextByte() * 10;. There are no arithmetic operations on byte or short. The value of keyboard.nextByte() is casted up to an int prior to multiplication with 10, which is also an int. The result of the multiplication is an int, which can not be stored into q1 if it's defined as a byte. Possible solutions would be to ...


10

While I can see why you would need to have a SmallObject, I would approach the problem differently. My approach to this type of issue is to use a Facade. Its sole purpose is to encapsulate BigObject and only make available specific members. In this way, it is a new interface on the same instance, and not a copy. Of course you may also want to perform a ...


9

Casting in C is unique, quite unlike other languages. It is also never intelligent. Casting in C converts values from one type to another using carefully defined rules. If you really need to know, read the standard. Otherwise the main points are: Conversion between integer types preserve the value, if possible. If the destination has more bits this is ...


8

Let's assume features start with 0 points, rather than with -100 points (due to costs associated with implementation, design, etc.). This feature strikes me as confusing. I've already declared that a is an A. If I want to know the compile-time type of a, I only have to look in one place, at the declaration. While I acknowledge that the implementation is ...


8

With other languages the situation is not so clear, but python happens to be specified in such a way that you can depend on it always casting to 1 and 0. Python's designers are some of the best with regard to the principle of least astonishment. The issue is that python is relatively rare as a first language, and programmers transfer practices from other ...


8

Languages that have implicit conversion to string usually have it for all types, not just numbers. Implicit conversions are usually bad if you want strong typing, type errors that could have been discovered in compile time(in case of compiled static-typed languages) or as exceptions in runtime(in case of interpreted or dynamic-typed languages) may turn into ...


8

If you have a method that needs to know whether the specific class is of type Human in order to do something, then you are breaking some SOLID principles, particularly : Open/closed principle - if, in the future, you need to add a new animal type that can speak (for example, a parrot), or do something specific for that type, your existing code will have to ...


8

It's a little hard to imagine a circumstance where you have a group of things and want them to either make a sandwich or contact aliens. In most cases where you find such casting you will operate with one type - e.g. in clang you filter a set of nodes for declarations where getAsFunction returns non-null, rather than doing something different for each node ...


7

The reason that you can't pass cons as an argument to foldl1 without casting is that the type of cons simply does not match that of foldl1's function argument and your cast is in fact illegal - but, sadly, unchecked, so you don't get an exception right away (you will get one eventually though). You've defined foldl1 to take a function that takes two ...


7

If writing code in C use a C cast. If writing in C++ use a C++ cast. Whilst most casting breaks proper type-safety, the C++ ones are more restrictive, and therefore you are slightly less type-unsafe than you would be with a C cast. I can tolerate someone using (T*)NULL though to force an overload...


7

The title of your question asks "is it a good idea" but the body asks "what is the correct way to do this?" I will address the concern in the title. At its core, a boolean is simply a single bit. However, it represents truth, not a number: while a bit may represent zero or one, it represents true and false when that bit is a boolean. What does "true" mean ...


7

Can anyone give a good example of when implementing explicit operator between unrelated types makes sense and how to do it? I will argue that it never makes sense to overload the explicit conversion operator. That operator has a well defined behavior, and using it for a different behavior will always fall into the realm of "clever". Just use a function. ...


6

You're mixing the weak/strong and dynamic/static type concepts. PHP is weak and dynamic, but your problem is with the dynamic type concept. That means, variables don't have a type, values do. A 'type casting' is an expression that produces a new value of a different type of the original; it doesn't do anything to the variable (if one is involved). The ...


6

I would call it cardinality (and indeed I have used it in that sense). It is strictly the cardinality of the set of all values a variable can take. Edit: for example, a 16-bit integer can take exactly 65536 values. The cardinality of the set of all values that the integer can take is 655536. Once you start to consider variables that have a range of valid ...


6

There is a very strong convention that casts on mutable reference types are identity-preserving. Because the system generally does not allow user-defined casting operators in situations where an object of the source type could be assigned to a reference of the destination type, there are only a few cases where user-defined casting operations would be ...


5

This is to some extent a matter of style, but I really believe your single-line option is much, much less readable, and is not a common approach. The first classic if is very easy to read and check. There's no complex nesting, just a plain, "boring", chain of conditions that is well understood in all languages that have an if/else if/else construct. The ...


5

I have a few rules about C/C++-style casts: Dis-applying a const must always use a const_cast. For obvious reasons. Sadly, my rule about dis-applying a const causing the keyboard to reach up and break the programmer's finger was not approved. Any of the bit-manipulation-style shenanigans that programmers get up to when getting down to the metal should use ...


4

If you know that everything in the scene is an instance of Sprite, then there should be no problem with typecasting. You can enable RTTI and use dynamic_cast<Sprite *> to be extra certain. If there may be other GraphicsItem elements that are not instances of Sprite, then you could keep a set (perhaps QSet<GraphicsItem *>) which holds pointers to ...


4

Theoretically speaking, the two concepts are vastly different: Type Casting refers to exchanging one type (roughly speaking, an object structure) for another while Type Conversion refers to translating of values (roughly speaking, contents of the object), so that they may be interpreted as belonging to a new type. Theoretically, they never mix. That said, ...


4

If you subscribe to the "types as a set of values" interpretation of type theory, then cardinality is in fact a good name. So, the cardinality of bool would be 2, the cardinality of byte would be 256, and the cardinality of String would be ℵ0.


4

As a data point, the Ceylon language allows1 you to do this. In Ceylon, you would write: A a = ... if (is B a) { // refer to 'a' as a 'B' } or if (is B b = some_expression_returning_A ) { // refer to 'b' as a 'B' } There is also a variation of the switch statement that allows you to switch on types, in much the same way. For example: void ...


4

I think one reason why this isn't widespread has to do with the meaning of names within a programming language. The fact that a class A has a field x and a class B also has a field x does not prove that these two fields are in any way comparable - one might be a value in a 2-D coordinate system and the other a dependent variable in a statistical modelling ...


4

Inheritance not helping to eliminate repetition and typecasts is often a sign that generics would help. You can do something like: public T getTranspose<T>() // or non-member function T getTranspose<T>(T input) I haven't fully worked it out, but it seems it might get awkward on the calling side. I know C# does some inference with generic ...



Only top voted, non community-wiki answers of a minimum length are eligible