Stack Exchange Network

Stack Exchange network consists of 174 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Questions tagged [type-casting]

Converting a variable from one type to another

2
votes
2answers
114 views

Primitive type conversion in computer graphics

I have been repeatedly told that explicit type conversions are an indicator of bad code and they should be avoided. Now in all honesty I have been annoyed a bit by these claims due to the nature of ...
1
vote
5answers
311 views

How to avoid the continuous downcasting in this case?

I have an abstract class Dog and multiple subclasses (Beagle, Labrador, Bulldog...) extendig it. I have a DogHouse that can store a Dog. My problem is that when I put for example a Beagle into a ...
1
vote
1answer
95 views

Making type conversions better readable

If you create a function, which should make the use of typeconversions more easy, but it maybe leads to more errors, would implement it globally, and what may speaks against it - when the readability ...
0
votes
1answer
52 views

Implicit conversion for function subtyping

Languages with coercions (i.e. implicit type conversions) allows expressing things like that (irrespective of any syntax): f : int32 → int32 = λx.x+x a : int16 = 42 b : int64 = f(a) Where type ...
0
votes
1answer
226 views

Using methods specific to a subclass

I came across this SESE page: What is a proper use of downcasting? (for C#) -- and it talks about when to downcast, and the possible downsides to it. In Python sub classes are slightly different ...
7
votes
2answers
3k views

Proper design to avoid the use of dynamic_cast?

After doing some researches I can not seem to find a simple example resolving a problem I encounter often. Let's say I want to create a little application where I can create Squares, Circles, and ...
4
votes
2answers
476 views

Can I use C-style casts when calling C functions from C++?

I have read, both on this site and elsewhere, that the recommended programming style for C++ is to avoid using C-style casts, and prefer the C++-style static_cast, dynamic_cast, reinterpret_cast, and ...
5
votes
1answer
1k views

Should I cast comparisons to NULL or nullptr?

Let's say I have a C++ function that looks like this: bool Foo(Bar* b) { if(b == nullptr) { return false; } // Do stuff return true; } Let's further say that, because of ...
0
votes
1answer
221 views

Type safety and runtime checking of type

I was mildly surprised to find this function in our code base: public static double ToDouble( object value ) { if ( value is double ) { return (double)value; } else if ( value is ...
1
vote
1answer
690 views

How to avoid the static_cast/dynamic_cast in `Abstract Factory` design pattern?

We are using Abstract Factory design pattern in our project, as the project became complex, most of the time the concrete class functionality need to separate to multiple class. As the following code ...
5
votes
2answers
535 views

Avoiding instanceof for recursive data types

I have written a simple class hierarchy to represent terms in Scala. Terms are recursive data types, e.g., a Sum and a Multiplication consist of the left-hand-side (lhs), which is a Term, and the ...
-2
votes
4answers
427 views

Best practice to avoid or refactor casting base type to derived class

I have an example about design patterns that demonstrates the adapter pattern. But I see casting to derived class here. That is not very good. If I meet such code in my practice, what is the best way ...
1
vote
2answers
392 views

How to avoid lots of ugly pointer casting when using a container in C?

Let's say I have a container in C, for example something similar to C++' std::deque: struct deque { // blah }; struct deque* deque_create(size_t element_size, size_t init_deq_size); void* ...
0
votes
2answers
2k views

Subclass to super class casting, C++

Out of curiosity. Say I have a class with a data member: class Base { public: //methods and constructor,set and get, operator overload etc private: int data; }; class Der : public Base { ...
1
vote
1answer
114 views

Is there a name for infered strong typing?

In JavaScript, you can have a loosely typed language. So doing the following is acceptable: var iterator = new TokenIterator(this.session, cursor.row, cursor.column); var matchType; var found = ...
1
vote
2answers
119 views

Should I return true in a method that casts null from one object type to another?

I'm writing a very simple extension method that attempts to cast objects from one type to another. The intent of having this method is very similar to Int32.TryParse(string, out int), which allows the ...
1
vote
1answer
138 views

Type Conversions in a dynamically typed language - Where should the conversion happen?

I was recently debugging a bit of code where the previous implementation looked something like this: # controller for group/customers def index @customers = current_user.available_customers(param[:...
-1
votes
1answer
982 views

Reuse base() constructor argument in this() constructor

Let's say I have two classes Base and Derived : Base. Derived shall be able to use a DerivedComponent : BaseComponent, just like all other derivates of Base use their own derivate specific component. ...
-2
votes
2answers
121 views

How is typecasting an array different from typecasting an individual element?

is the following code snippet: String[] str = {"Abc","Ghi","Def","Mno"}; Object[] obj = str; String[] p = (String[]) obj; same as : String[] str = {"Abc","...
7
votes
3answers
14k views

Is it a good practice to use suppress warnings in your code?

I use @SuppressWarnings("unchecked") and @SuppressWarnings("null") mostly above methods to let the code compile without any warnings but I have my doubts. Found this Stackoverflow question. Jon Skeet ...
6
votes
2answers
227 views

Casting a nullary data constructor between types

Suppose I have a parametrized data type with more than one nullary (constant) data constructor, such as: data Check a = Valid | Invalid | Unsure a Sometimes I want to manipulate the non-constant ...
0
votes
2answers
172 views

Is it bad practice to verify arguments passed to a function? [duplicate]

I find myself writing a lot of functions whereby the first few lines "verify" the arguments, that is, they typecast, check falseness, range, etc. before doing any work. The main reasoning for this is ...
1
vote
2answers
52 views

Are Data defined into derived class saved when up-casting?

Let's say i have two class named Object (base class) and an actor class (derived class). The actor class uses physics so i need to implement it on the Actor class. But there are other derived class of ...
0
votes
0answers
103 views

Arbitrarily sized (and signedness) integer arithmetic in C++ - How can it be done generically at runtime?

How can I efficiently handle integers of unknown size and signedness in various arithmetical operations in C++? (for a virtual machine). I am storing the program for the virtual machine in a string ...
0
votes
3answers
245 views

Is there any technical reason to be concerned with casting speed?

So, I'm working on a project that takes a very complex entity from a third party framework and converts it into the native object that defines that entity. This entity has several one-to-many ...
0
votes
0answers
128 views

Type checking in factory, bad practice?

I'm working on an existing code base and am trying to reduce a lot of duplication and gain some polymorphic behavior. Right now I have a type of domain object with an abstract base class and two (at ...
3
votes
3answers
173 views

How to design access to different type objects in protocol response

I have written a communication library for an industrial device protocol. The response frame contains a byte array as payload data. The payload data consists of several "objects“ of different types, ...
5
votes
1answer
4k views

What is the motivation for casting a pointer into a integer?

I'm doing some changes in the Linux kernel code and have noticed a pointer being cast into integer. Check out buf below (full code): snd_pcm_sframes_t snd_pcm_lib_read(struct snd_pcm_substream *...
6
votes
2answers
192 views

Is it possible to avoid abstraction inversion in this scenario?

I'm designing a library built on web scraping that tries to provide an API to a popular news site. I am representing each of its articles as a collection of 'elements' (IElement), such as images, ...
2
votes
1answer
191 views

Storing values in SQL whose types are determined in runtime

I have come across a need of storing runtime determined values in a SQL database. For example, there is a GUI where a user can add new editable fields. So the user adds a field Name, chooses the ...
3
votes
2answers
1k views

When it makes sense to implement C# explicit operator?

Follow-up of Is my usage of explicit casting operator reasonable or a bad hack? One of the users commenting on that question said that it's really bad if the casting operator creates a new object ...
24
votes
5answers
6k views

Is my usage of explicit casting operator reasonable or a bad hack?

I have a big object: class BigObject{ public int Id {get;set;} public string FieldA {get;set;} // ... public string FieldZ {get;set;} } and a specialized, DTO-like object: class ...
33
votes
10answers
7k views

Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses?

I have a base class, Base. It has two subclasses, Sub1 and Sub2. Each subclass has some additional methods. For example, Sub1 has Sandwich makeASandwich(Ingredients... ingredients), and Sub2 has ...
3
votes
3answers
930 views

“One of some”-type

Say that you have some different classes that does not really have any functionality in common, but somewhere in your program, you need one of them (which one is not necessarily important) because ...
2
votes
1answer
2k views

Constructor vs casting operator

I'm programming a library (so I have complete access to all the mentioned classes). Two classes (A and B) are essentially the same and differ only by their implementation, so they can easily be ...
8
votes
4answers
23k views

OOD: Java inheritance and access to child methods via casting

I have several classes Parent and Child1 ... Child9 implemented in Java. Parent is an abstract class, containing all the common variables of the child classes (a lot, which is the main reason why I ...
1
vote
1answer
158 views

Ignoring the generic part of a type while an object is being passed

I have a message class that holds the name of a destination, and a generic variable acting as the message payload public class Message<T> { public string Destination public T Payload ...
4
votes
2answers
9k views

Having an inherited function return the derived type instead of the base type

I am writing two classes in C#: A Matrix class that represents a general Matrix with n-by-m dimensions A SquareMatrix class that inherits from Matrix and has the constraint of being n-by-n The ...
1
vote
3answers
102 views

Property-level value transformation for indirect object casting

Does any programming language exist to support the explicit, property-level object copy? For example, assume this code: public class Student { public string Name { get; set; } public string ...
1
vote
3answers
7k views

Make Return Type an Interface - Problem with Initialization

I would like to make the return type of my method an interface rather than a class for similar reasons stated in c# List or IList, however I am having trouble figuring out how to initialize the ...
2
votes
2answers
14k views

A vector of pointers to different derived classes of the same base class

I am writing a game in C++ which has different enemy types. I have defined a base Enemy class and I also have derived classes enemy1, enemy2 etc. Now for updating these enemies in each iteration of ...
10
votes
6answers
11k views

How to avoid downcasting?

My question is about a special case of the super class Animal. My Animal can moveForward() and eat(). Seal extends Animal. Dog extends Animal. And there's a special creature that also extends ...
2
votes
1answer
113 views

Handling Types for Real and Complex Matrices in a BLAS Wrapper

I come from a C background and I'm now learning OOP with C++. As an exercise (so please don't just say "this already exists"), I want to implement a wrapper for BLAS that will let the user write ...
0
votes
2answers
14k views

Question about casting a class in Java with generics

In Java 6 Class<? extends ArrayList<?>> a = ArrayList.class; gives and error, but Class<? extends ArrayList<?>> b = (Class<? extends ArrayList<?>>)ArrayList....
1
vote
2answers
7k views

Why doesn't Ruby have implicit conversion of Fixnum into String?

Ruby normally makes things easy. However, it doesn't allow implicitely converting a number to a string: 2.0.0p247 :010 > "a"+1 TypeError: no implicit conversion of Fixnum into String Why is this ...
0
votes
3answers
6k views

Is converting/casting a boolean to int a good idea? [closed]

Note: Even though this contains Python, it's not specifically about Python. It's more generally about expecting a certain behaviour from a language which is not necessarily the same across compilers/...
1
vote
2answers
284 views

Optimization ended up in casting an object at each method call

I've been doing some optimization for the following piece of code : public void DrawLine(int x1, int y1, int x2, int y2, int color) { _bitmap.DrawLineBresenham(x1, y1, x2, y2, color); } After ...
6
votes
9answers
2k views

Would a “downcast if block” be a reasonable language feature?

Consider the following "if cast": class A { public void f1() { ... } } class B : A { public void f2() { ... } } A a = foo(); // might return A or B if ( a is B ) { // Inside block, ...
1
vote
1answer
67 views

Removing dependencies on subclass-specific behavior

I have a Message class which can contain multiple types of payloads (or sometimes no payload), each derived from a common Payload class. However, this becomes problematic because the Message class ...
5
votes
2answers
417 views

Is there a name for the number of values a variable can take? [closed]

For example, a bit or a boolean can be either 0 or 1 so the number 2 is associated with it. Similarly, for a byte which is 8 bits, the maximum number of different assignments would be 2^8. Is there a ...