Search Results

Search found 20 results on 1 pages for 'downcasting'.

Page 1/1 | 1 

  • Is this not downcasting?

    - by cambr
    If I do double d = 34.56; int i = (int)d; Am I not "downcasting"? OR Is this term only used in terms of classes and objects? I am confused because in this case we are "downcasting" from a bigger double to a smaller int, but in case of classes, we "downcast" from a smaller base class to a bigger derived class. Aren't these two conventions, in some sense, opposite?

    Read the article

  • What is upcasting/downcasting?

    - by acidzombie24
    When learning about polymorphism you commonly see something like this class Base { int prv_member; virtual void fn(){} } class Derived : Base { int more_data; virtual void fn(){} } What is upcasting or downcasting? Is (Derived*)base_ptr; an upcast or downcast? I call it upcast because you are going away from the base into something more specific. Other people told me it is a downcast because you are going down a hierarchy into something specific with the top being the root. But other people seem to call it what i call it. When converting a base ptr to a derived ptr is it called upcasting or downcasting? and if someone can link to an official source or explain why its called that than great.

    Read the article

  • Shallow copying a list with downcasting

    - by Mohit
    I have the class herichary as follows CEntity----CNode---CElement I have a class Nodes : List<Cnode> and Class Elements : List<Element> Node class contain common item common across different project Element class has item specific to a project. I have to shallow copy the element list into the node list (basically down casting the elements to nodes)

    Read the article

  • Java downcasting and is-A has-A relationship

    - by msharma
    HI, I have a down casting question, I am a bit rusty in this area. I have 2 clasess like this: class A{ int i; String j ; //Getters and setters} class B extends A{ String k; //getter and setter} I have a method like this, in a Utility helper class: public static A converts(C c){} Where C are objects that are retireved from the database and then converted. The problem is I want to call the above method by passing in a 'C' and getting back B. So I tried this: B bClasss = (B) Utility.converts(c); So even though the above method returns A I tried to downcast it to B, but I get a runtime ClassCastException. Is there really no way around this? DO I have to write a separate converts() method which returns a B class type? If I declare my class B like: class B { String k; A a;} // So instead of extending A it has-a A, getter and setters also then I can call my existing method like this: b.setA(Utility.converts(c) ); This way I can reuse the existing method, even though the extends relationship makes more sense. What should I do? Any help much appreciated. Thanks.

    Read the article

  • java: "downcasting" to new object / opposite of slicing

    - by rhavin
    Sorry, i really dont know how to make a headline for that question; maybe there is a name for what im trying to do that i dont know, but i can explain it with some code: Guess you have a class that unfortunately neither has a copy-constructor nor a public static copy method. class A { private int i; // <- private, cant access String x; // <- even worse: cant access unless in same pkg! /* … other stuff, ctor, etc. … */ public A clone() { A a = new A(); a.i = i; a.x = x; return x; } } Guess further, there is some function that returns an object of that class: public static A someFn(x,y,z); Now the problem: I want to derive from that class to add some functionality. Unfortunately, i neither have a sizeof in java nor a cc or static copy method. So when i do a class B extends A { protected w; public B clone() { /* as usual */ } } then i can clone my B and get a new one, but how can i convert the returned A from someFn() into a B. Is there anyway to do the opposite of slicing in java? if i clone it, it's still an A, and i cant copy it field by field. This is all simple in c++, but how to do this in Java?

    Read the article

  • Should downcasting be avoided while using a class hierarchy in C++?

    - by neuviemeporte
    Let's say I'm writing an application which works with projects, and exposes different functionality depending on the type of the project. I have a hierarchy of classes for the different types of projects: class AbstractProject { }; class ProjectA : public AbstractProject { }; class ProjectB : public AbstractProject { }; class ProjectC : public AbstractProject { }; Now, I was planning to have an AbstractProject *_currentProject pointer as a member in the application's main class, pop up a dialog box on startup and based on the selection, do: _currentProject = new ProjectB(); // e.g. Later, I'll have to downcast the pointer to the specific type to utilize the functionality specific to different Project-s. Somehow this makes me feel uneasy. Is there a Better Way of doing this?

    Read the article

  • Java downcasting dilemma

    - by Shades88
    please have a look at this code here. class Vehicle { public void printSound() { System.out.print("vehicle"); } } class Car extends Vehicle { public void printSound() { System.out.print("car"); } } class Bike extends Vehicle{ public void printSound() { System.out.print("bike"); } } public class Test { public static void main(String[] args) { Vehicle v = new Car(); Bike b = (Bike)v; v.printSound(); b.printSound(); Object myObj = new String[]{"one", "two", "three"}; for (String s : (String[])myObj) System.out.print(s + "."); } } Executing this code will give ClassCastException saying inheritance.Car cannot be cast to inheritance.Bike. Now look at the line Object myObj = new String[]{"one", "two", "three"};. This line is same as Vehicle v = new Car(); right? In both lines we are assigning sub class object to super class reference variable. But downcasting String[]myObj is allowed but (Bike)v is not. Please help me understand what is going on around here.

    Read the article

  • How to properly downcast in C# with a SWIG generated interface?

    - by JG
    I've got a very large and mature C++ code base that I'm trying to use SWIG on to generate a C# interface for. I cannot change the actual C++ code itself but we can use whatever SWIG offers in the way of extending/updating it. I'm facing an issue where a function C++ is written as such: A* SomeClass::next(A*) The caller might do something like: A* acurr = 0; while( (acurr = sc->next(acurr)) != 0 ){ if( acurr isoftype B ){ B* b = (B*)a; ...do some stuff with b.. } elseif( acurr isoftype C ) ... } Essentially, iterating through a container elements that depending on their true type, do something different. The SWIG generated C# layer for the "next" function unfortunately does the following: return new A(); So the calling code in C# land cannot determine if the returned object is actually a derived class or not, it actually appears to always be the base class (which does make sense). I've come across several solutions: Use the %extend SWIG keyword to add a method on an object and ultimately call dynamic_cast. The downside to this approach, as I see it, is that this requires you to know the inheritance hierarchy. In my case it is rather huge and I see this is as a maintenance issue. Use the %factory keyword to supply the method and the derived types and have SWIG automatically generate the dynamic_cast code. This appears to be a better solution that the first, however upon a deeper look it still requires you to hunt down all the methods and all the possible derived types it could return. Again, a huge maintenance issue. I wish I had a doc link for this but I can't find one. I found out about this functionality by looking through the example code that comes with SWIG. Create a C# method to create an instance of the derived object and transfer the cPtr to the new instance. While I consider this clumsy, it does work. See an example below. public static object castTo(object fromObj, Type toType) { object retval = null; BaseClass fromObj2 = fromObj as BaseClass; HandleRef hr = BaseClass.getCPtr(fromObj2); IntPtr cPtr = hr.Handle; object toObj = Activator.CreateInstance(toType, cPtr, false); // make sure it actually is what we think it is if (fromObj.GetType().IsInstanceOfType(toObj)) { return toObj; } return retval; } Are these really the options? And if I'm not willing to dig through all the existing functions and class derivations, then I'm left with #3? Any help would be appreciated.

    Read the article

  • Are there any C++ tools that detect misuse of static_cast, dynamic_cast, and reinterpret_cast?

    - by chrisp451
    The answers to the following question describe the recommended usage of static_cast, dynamic_cast, and reinterpret_cast in C++: http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used Do you know of any tools that can be used to detect misuse of these kinds of cast? Would a static analysis tool like PC-Lint or Coverity Static Analysis do this? The particular case that prompted this question was the inappropriate use of static_cast to downcast a pointer, which the compiler does not warn about. I'd like to detect this case using a tool, and not assume that developers will never make this mistake.

    Read the article

  • Java: Reflection against casting when you know superclass

    - by Ema
    I don't know exactly how to define my doubt so please be patient if the question has already been asked. Let's say I have to dinamically instantiate an object. This object will surely be instance of a subclass of a known, immutable class A. I can obtain dinamically the specific implementation class. Would it be better to use reflection exactly as if I didn't know anything about the target class, or would it be preferrable/possible to do something like: A obj = (Class.forName("com.package.Sub-A")) new A(); where Sub-A extends A ? The purpose would be to avoid reflection overhead times... Thank you in advance.

    Read the article

  • Invoke a subclass method of an anonymous class

    - by arjacsoh
    I am trying right now to dig into anonymous classes and one question was just arised I 'd prefer not to refer to much details and to pose my question straightforward: How can I invoke the method sizzle() in the following anonymous class: public class Popcorn { public void pop() { System.out.println("popcorn"); } } class Food { Popcorn p = new Popcorn() { public void sizzle() { System.out.println("anonymous sizzling popcorn"); } public void pop() { System.out.println("anonymous popcorn"); } }; public void popIt() { p.pop(); // OK, Popcorn has a pop() method p.sizzle(); // Not Legal! Popcorn does not have sizzle() } } It is known and definite in polymorphism rules that a refernce of a superclass cannot invoke methods of subclass without downcasting (even if it refers to an object of the given subclass). However in the above case what is the "key" to invoke the sizzle() method?

    Read the article

  • Return an opaque object to the caller without violating type-safety

    - by JS Bangs
    I have a method which should return a snapshot of the current state, and another method which restores that state. public class MachineModel { public Snapshot CurrentSnapshot { get; } public void RestoreSnapshot (Snapshot saved) { /* etc */ }; } The state Snapshot class should be completely opaque to the caller--no visible methods or properties--but its properties have to be visible within the MachineModel class. I could obviously do this by downcasting, i.e. have CurrentSnapshot return an object, and have RestoreSnapshot accept an object argument which it casts back to a Snapshot. But forced casting like that makes me feel dirty. What's the best alternate design that allows me to be both type-safe and opaque?

    Read the article

  • casting Collection<SomeClass> to Collection<SomeSuperClass>

    - by skrebbel
    Hi all, I'm sure this has been answered before, but I really cannot find it. I have a java class SomeClass and an abstract class SomeSuperClass. SomeClass extends SomeSuperClass. Another abstract method has a method that returns a Collection<SomeSuperClass>. In an implementation class, I have a Collection<SomeClass> myCollection I understand that I cannot just return myCollection, because Collection<SomeClass> does not inherit from Collection<SomeSuperClass>. Nevertheless, I know that everything in myCollection is a SomeSuperClass because after all, they're SomeClass objects which extend SomeSuperClass. How can I make this work? I.e. I want public class A { private Collection<SomeClass> myCollection; public Collection<SomeSuperClass> getCollection() { return myCollection; //compile error! } } The only way I've found is casting via a non-generic type and getting unchecked warnings and whatnot. There must be a more elegant way, though? I feel that also using Collections.checkedSet() and friends are not needed, since it is statically certain that the returned collection only contains SomeClass objects (this would not be the case when downcasting instead of upcasting, but that's not what I'm doing). What am I missing? Thanks!

    Read the article

  • How do actually castings work at the CLR level?

    - by devoured elysium
    When doing an upcast or downcast, what does really happen behind the scenes? I had the idea that when doing something as: string myString = "abc"; object myObject = myString; string myStringBack = (string)myObject; the cast in the last line would have as only purpose tell the compiler we are safe we are not doing anything wrong. So, I had the idea that actually no casting code would be embedded in the code itself. It seems I was wrong: .maxstack 1 .locals init ( [0] string myString, [1] object myObject, [2] string myStringBack) L_0000: nop L_0001: ldstr "abc" L_0006: stloc.0 L_0007: ldloc.0 L_0008: stloc.1 L_0009: ldloc.1 L_000a: castclass string L_000f: stloc.2 L_0010: ret Why does the CLR need something like castclass string? There are two possible implementations for a downcast: You require a castclass something. When you get to the line of code that does an castclass, the CLR tries to make the cast. But then, what would happen had I ommited the castclass string line and tried to run the code? You don't require a castclass. As all reference types have a similar internal structure, if you try to use a string on an Form instance, it will throw an exception of wrong usage (because it detects a Form is not a string or any of its subtypes). Also, is the following statamente from C# 4.0 in a Nutshell correct? Upcasting and downcasting between compatible reference types performs reference conversions: a new reference is created that points to the same object. Does it really create a new reference? I thought it'd be the same reference, only stored in a different type of variable. Thanks

    Read the article

  • Force calling the derived class implementation within a generic function in C#?

    - by Adam Hardy
    Ok so I'm currently working with a set of classes that I don't have control over in some pretty generic functions using these objects. Instead of writing literally tens of functions that essentially do the same thing for each class I decided to use a generic function instead. Now the classes I'm dealing with are a little weird in that the derived classes share many of the same properties but the base class that they are derived from doesn't. One such property example is .Parent which exists on a huge number of derived classes but not on the base class and it is this property that I need to use. For ease of understanding I've created a small example as follows: class StandardBaseClass {} // These are simulating the SMO objects class StandardDerivedClass : StandardBaseClass { public object Parent { get; set; } } static class Extensions { public static object GetParent(this StandardDerivedClass sdc) { return sdc.Parent; } public static object GetParent(this StandardBaseClass sbc) { throw new NotImplementedException("StandardBaseClass does not contain a property Parent"); } // This is the Generic function I'm trying to write and need the Parent property. public static void DoSomething<T>(T foo) where T : StandardBaseClass { object Parent = ((T)foo).GetParent(); } } In the above example calling DoSomething() will throw the NotImplemented Exception in the base class's implementation of GetParent(), even though I'm forcing the cast to T which is a StandardDerivedClass. This is contrary to other casting behaviour where by downcasting will force the use of the base class's implementation. I see this behaviour as a bug. Has anyone else out there encountered this?

    Read the article

  • Any way to allow classes implementing IEntity and downcast to have operator == comparisons?

    - by George Mauer
    Basically here's the issue. All entities in my system are identified by their type and their id. new Customer() { Id = 1} == new Customer() {Id = 1}; new Customer() { Id = 1} != new Customer() {Id = 2}; new Customer() { Id = 1} != new Product() {Id = 1}; Pretty standard scenario. Since all Entities have an Id I define an interface for all entities. public interface IEntity { int Id { get; set;} } And to simplify creation of entities I make public abstract class BaseEntity<T> : where T : IEntity { int Id { get; set;} public static bool operator ==(BaseEntity<T> e1, BaseEntity<T> e2) { if (object.ReferenceEquals(null, e1)) return false; return e1.Equals(e2); } public static bool operator !=(BaseEntity<T> e1, BaseEntity<T> e2) { return !(e1 == e2); } } where Customer and Product are something like public class Customer : BaseEntity<Customer>, IEntity {} public class Product : BaseEntity<Product>, IEntity {} I think this is hunky dory. I think all I have to do is override Equals in each entity (if I'm super clever, I can even override it only once in the BaseEntity) and everything with work. So now I'm expanding my test coverage and find that its not quite so simple! First of all , when downcasting to IEntity and using == the BaseEntity< override is not used. So what's the solution? Is there something else I can do? If not, this is seriously annoying. Upadate It would seem that there is something wrong with my tests - or rather with comparing on generics. Check this out [Test] public void when_created_manually_non_generic() { // PASSES! var e1 = new Terminal() {Id = 1}; var e2 = new Terminal() {Id = 1}; Assert.IsTrue(e1 == e2); } [Test] public void when_created_manually_generic() { // FAILS! GenericCompare(new Terminal() { Id = 1 }, new Terminal() { Id = 1 }); } private void GenericCompare<T>(T e1, T e2) where T : class, IEntity { Assert.IsTrue(e1 == e2); } Whats going on here? This is not as big a problem as I was afraid, but is still quite annoying and a completely unintuitive way for the language to behave. Update Update Ah I get it, the generic implicitly downcasts to IEntity for some reason. I stand by this being unintuitive and potentially problematic for my Domain's consumers as they need to remember that anything happening within a generic method or class needs to be compared with Equals()

    Read the article

  • C++ game designing & polymorphism question

    - by Kotti
    Hi! I'm trying to implement some sort of 'just-for-me' game engine and the problem's plot goes the following way: Suppose I have some abstract interface for a renderable entity, e.g. IRenderable. And it's declared the following way: interface IRenderable { // (...) // Suppose that Backend is some abstract backend used // for rendering, and it's implementation is not important virtual void Render(Backend& backend) = 0; }; What I'm doing right now is something like declaring different classes like class Ball : public IRenderable { virtual void Render(Backend& backend) { // Rendering implementation, that is specific for // the Ball object // (...) } }; And then everything looks fine. I can easily do something like std::vector<IRenderable*> items, push some items like new Ball() in this vector and then make a call similiar to foreach (IRenderable* in items) { item->Render(backend); } Ok, I guess it is the 'polymorphic' way, but what if I want to have different types of objects in my game and an ability to manipulate their state, where every object can be manipulated via it's own interface? I could do something like struct GameState { Ball ball; Bonus bonus; // (...) }; and then easily change objects state via their own methods, like ball.Move(...) or bonus.Activate(...), where Move(...) is specific for only Ball and Activate(...) - for only Bonus instances. But in this case I lose the opportunity to write foreach IRenderable* simply because I store these balls and bonuses as instances of their derived, not base classes. And in this case the rendering procedure turns into a mess like ball.Render(backend); bonus.Render(backend); // (...) and it is bad because we actually lose our polymorphism this way (no actual need for making Render function virtual, etc. The other approach means invoking downcasting via dynamic_cast or something with typeid to determine the type of object you want to manipulate and this looks even worse to me and this also breaks this 'polymorphic' idea. So, my question is - is there some kind of (probably) alternative approach to what I want to do or can my current pattern be somehow modified so that I would actually store IRenderable* for my game objects (so that I can invoke virtual Render method on each of them) while preserving the ability to easily change the state of these objects? Maybe I'm doing something absolutely wrong from the beginning, if so, please point it out :) Thanks in advance!

    Read the article

  • Explicit method tables in C# instead of OO - good? bad?

    - by FunctorSalad
    Hi! I hope the title doesn't sound too subjective; I absolutely do not mean to start a debate on OO in general. I'd merely like to discuss the basic pros and cons for different ways of solving the following sort of problem. Let's take this minimal example: you want to express an abstract datatype T with functions that may take T as input, output, or both: f1 : Takes a T, returns an int f2 : Takes a string, returns a T f3 : Takes a T and a double, returns another T I'd like to avoid downcasting and any other dynamic typing. I'd also like to avoid mutation whenever possible. 1: Abstract-class-based attempt abstract class T { abstract int f1(); // We can't have abstract constructors, so the best we can do, as I see it, is: abstract void f2(string s); // The convention would be that you'd replace calls to the original f2 by invocation of the nullary constructor of the implementing type, followed by invocation of f2. f2 would need to have side-effects to be of any use. // f3 is a problem too: abstract T f3(double d); // This doesn't express that the return value is of the *same* type as the object whose method is invoked; it just expresses that the return value is *some* T. } 2: Parametric polymorphism and an auxilliary class (all implementing classes of TImpl will be singleton classes): abstract class TImpl<T> { abstract int f1(T t); abstract T f2(string s); abstract T f3(T t, double d); } We no longer express that some concrete type actually implements our original spec -- an implementation is simply a type Foo for which we happen to have an instance of TImpl. This doesn't seem to be a problem: If you want a function that works on arbitrary implementations, you just do something like: // Say we want to return a Bar given an arbitrary implementation of our abstract type Bar bar<T>(TImpl<T> ti, T t); At this point, one might as well skip inheritance and singletons altogether and use a 3 First-class function table class /* or struct, even */ TDictT<T> { readonly Func<T,int> f1; readonly Func<string,T> f2; readonly Func<T,double,T> f3; TDict( ... ) { this.f1 = f1; this.f2 = f2; this.f3 = f3; } } Bar bar<T>(TDict<T> td; T t); Though I don't see much practical difference between #2 and #3. Example Implementation class MyT { /* raw data structure goes here; this class needn't have any methods */ } // It doesn't matter where we put the following; could be a static method of MyT, or some static class collecting dictionaries static readonly TDict<MyT> MyTDict = new TDict<MyT>( (t) => /* body of f1 goes here */ , // f2 (s) => /* body of f2 goes here */, // f3 (t,d) => /* body of f3 goes here */ ); Thoughts? #3 is unidiomatic, but it seems rather safe and clean. One question is whether there are any performance concerns with it. I don't usually need dynamic dispatch, and I'd prefer if these function bodies get statically inlined in places where the concrete implementing type is known statically. Is #2 better in that regard?

    Read the article

1