problem about downcasting-Collection of common programming errors

dragonaid
java casting downcasting
This question already has an answer here:Downcasting in Java8 answersCan anyone here please explain to me why I get a java.lang.ClassCastException when downcasting a Parent to a Child?public class Child extends Parent{ public static void main(String[] args){new Child().go(); } void go(){go2(new Parent(), new Child());go2((Child) new Parent(), new Child()); } void go2(Parent p1, Child c1){Child c2 = (Child)p1;Parent p2 = (Parent)c1; } } class Tree{}I have read reference variable casting and sear
Mastergeek
java object casting double downcasting
Say I have this:Object obj = new Double(3.14);Is there a way to use obj like a Double without explicitly casting it to Double? For instance, if I wanted to use the .doubleValue() method of Double for calculations.
AlienArrays
java inheritance object polymorphism downcasting
I was trying to do something likeclass O has a child EI declare the variable O xyz = new E();but then if I call xyz.method(), I can only call those in class O’s methods, not E’s, so I can downcast it byE xyz2 = (E) xyz;My question is- Can you do this without declaring a new variable? Something like:O xyz = new E(); xyz = (E) xyz; and now I can use xyz.method() to call E’s methods Is there a way to do this in java?
Alex Shesterov
java list inheritance casting downcasting
I’m having trouble casting a List of Fruit down to the Fruit subclass contained in the List. public class Response {private List<Fruit> mFruitList;public List<Fruit> getFruitList() {return mFruitList;} } public class Fruit { }public class Orange extends Fruit { }List<Fruit> oranges = response.getFruitList();How do I cast oranges so that it is a List of class Orange? Is this a bad design pattern? Basically I am getting a JSON Response from a server that is a List of Fruit. For
Syed Zahid Ali
java object arraylist downcasting up-casting
I have a situation in which I am getting data from database, and I want to upcast it to ArrayList of objects and then downcast it to different custom ArrayList i.e. List<User>, List<Groups> etc.My question is up-casting to object and then down-casting to ArrayList, what will be the cost, and is it efficient or good practice.EDITEDInstead of getting data as List<User>, List<Groups> etc I want to get data as ArrayList<objetcs> once and then as per my need, I will dow
curiousguy
c++ multiple-inheritance dynamic-cast downcasting virtual-inheritance
I tried creating a class that inherits from multiple classes as followed, getting a “diamond” (D inherits from B and C. B and C both inherits from A virtually): A / \B C \ / DNow, I have a container with a linked list that holds pointers to the base class (A). When I tried doing explicit casting to a pointer (after typeid check) I got the following error: “cannot convert a pointer to base class “A” to pointer to derived class “D” — base class is virtual”
Birdman
java swing awt graphics2d downcasting
I’m trying to figure out why it is allowed to downcast a Graphics instance to a Graphics2D instance.It’s usually against the rules to downcast a reference type that isn’t inheriting the target type.In the graphic-oriented classes the hierarchy is like the following:Graphics is the superclass Graphics2D is the subclass of the superclass GraphicsWhen drawing something in Swing you override the paint() method – And if you’re in need of 2D-drawing you downcast the automatically supplied Graphics ins
Klamann
java class generics downcasting
In a generic method, I don’t seem to be able to access the generic type of the method at runtime (error: cannot select from a type variable).public <A> A get(Animal a) {Class ac = a.getClass();if(ac.isAssignableFrom(A.class)) { // <- not working!return (A) a;} else {// error handling} }The reason why I do this is to be able to safely downcast stuff, like:Animal a = new Dog(); Dog d = get(a); // <- OK Cat c = get(a) // <- incompatible types, caught by else blockI’ve found a
Sudheer
java casting type-conversion downcasting downcast
public class InheritanceDemo {public static void main(String[] args) {ParentClass p = new ParentClass();ChildClass c = new ChildClass();//Casting ChildClass to ParentClassParentClass pc = new ChildClass();pc.parentClassMethod(); //Output: Parent Class Method (as expected)//Again Casting Parent Class to ChildClass explictly//Question 1 for this codeChildClass cp = (ChildClass) pc;cp.parentClassMethod(); //Output: Parent Class Method (unexpected)ChildClass cc1 = (ChildClass) new ParentClass();cc1.
Buhake Sindi
java downcasting
Run time exception– java.lang.ClassCastingException…Integer intArr[] = new Integer[arrList.size()]; ArrayList <Integer> arrList =new ArrayList(); intArr=(Integer[])arrList.toArray(); // returns Object class which is downcaste to Integer;I understand down-casting is not safe but why is this happening? I also tried to converting ArrayList to String to Integer to int, but I get the same error.
ekkis
c# entity-framework asp.net-mvc-3 casting downcasting
I have a project where I’ve defined in EF an Employer as a derived class of User. In my process I create a user without knowing whether it will eventually be an employer (or other kinds of users) and later I need to convert it. At first I tried (Intellisense indicated an explicit conversion exists):Employer e = (Employer) GetUser();but at runtime I got:Unable to cast object of type ‘System.Data.Entity.DynamicProxies.User_7B…0D’ to type ‘Employer’.so I tried to write a converter:public partia
Ziv
c++ casting private downcasting
A tweak on this question that I’ve run into. Consider:class A {};class B : private A {static void foo(); };void B::foo(){B* bPtr1 = new B;A* aPtr1 = dynamic_cast<A*>(bPtr1); // gives pointerB* bPtr2 = dynamic_cast<B*>(aPtr1); // gives NULL }Since aPtr1 is, in fact, of type B*, and since we’ve got full access to B and its inheritance from A, I’d expected both casts to work. But they don’t; why? Is there another way to achieve this cast?Note that:If foo() were not a member of B, both c
Abruzzo Forte e Gentile
c++ casting downcasting
I am reviewing C++ casts operator and I have the following doubt:for polymorphic classes I I should use polymorphic_cast I should never use of static_cast since down-casting might carry to undefined behavior. The code compiles this case anyway.Now suppose that I have the following situtationclass CBase{}; class CDerived : public CBase{};int main( int argc, char** argv ){CBase* p = new CDerived();//.. do somethingCDerived*pd = static_cast<CDerived*>( p ); }Since there is no polymorphism in
jedwards
c++ stl shared-ptr downcasting
Consider the following outline:class Base { /* … */ };class Derived : public Base { public:void AdditionalFunctionality(int i){ /* … */ } };typedef std::shared_ptr<Base> pBase; typedef std::shared_ptr<Derived> pDerived;int main(void) {std::vector<pBase> v;v.push_back(pBase(new Derived()));pDerived p1( std::dynamic_pointer_cast<Derived>(v[0]) ); /* Copy */pDerived p2 = std::dynamic_pointer_cast<Derived>(v[0]); /* Assignment */p1->AdditionalFunctionality(1
Lightness Races in Orbit
c++ virtual-inheritance downcasting static-cast
Consider the following code:struct Base {}; struct Derived : public virtual Base {};void f() {Base* b = new Derived;Derived* d = static_cast<Derived*>(b); }This is prohibited by the standard ([n3290: 5.2.9/2]) so the code does not compile, because Derived virtually inherits from Base. Removing the virtual from the inheritance makes the code valid.What’s the technical reason for this rule to exist?
CodeKingPlusPlus
c++ inheritance casting downcasting downcast
I have my base class as follows: class point //concrete class {… //implementation }class subpoint : public point //concrete class { … //implementation }How do I cast from a point object to a subpoint object? I have tried all three of the following:point a; subpoint* b = dynamic_cast<subpoint*>(&a); subpoint* b = (subpoint*)a; subpoint b = (subpoint)a;What is wrong with these casts?
huy
c++ downcasting
I have a simple hierarchy tree structure with a base class Node representing a node. A node could be of another specific type (subclassing).class Node {vector<Node*> childs;// simple node manipulation methodsconst vector<Node*>& getChildren() { return childs; } }and I have a couple of subclasses of Node:class FacultyNode : public Node; … class DepartmentNode : public Node; …Say I know that all children of a faculty node is of DepartmentNode type, to save the developer’s work
nahpr
c++ void-pointers downcasting
So I go this:class A;class B : public A;class C : public B;vector<A*> *vecA;vector<C*> *vecC;And I want to cast a vectC into a vecA.vector<A*> *_newA = static_cast< vector<A*>* >(vecC); //gives an errorSo I used void pointer as a buffer and the cast:void *buffer = vecC;vector<A*> *_newA = static_cast< vector<A*>* >(buffer); //worksIs this valid? Is there another way to do it?
Alex
c++ polymorphism downcasting up-casting
I have the following classes:class State {protected:Vec3D accel;Vec3D gyro;Vec3D gps;float reward;public:boost::ptr_vector<Action> actions;…virtual bool isTerm(); }class guState : public State { float gps_stand_thres;float gps_down_thres;public:guState(Agent &A,ACTION_MODE &m);bool isTerm(); };There are other classes which all inherit from State. Their differences solely lie on how they evaluate isTerm() which depends on behavior. I would rather not use virtual functions bur ove
Sumit Das
c++ inheritance downcasting
Here’s a piece of code I had written to see the behaviour during downcasting.#include <iostream> using namespace std;class base { public :void function(){cout << “\nInside class Base”;} };class derived : public base { public :void function(){cout << “\nInside class Derived.”;} };int main() {base * b1 = new base();base * b2 = new derived();derived * b3 = (derived*)b1 ;b1 -> function();b2 -> function();b3 -> function(); // print statement 3static_cast<derived*>(b2)
Bogdan Vasilescu
c pointers type-conversion downcasting
Pointer Downcastint* ptrInt;char * ptrChar;void* ptrVoid;unsigned char indx;int sample = 0x12345678;ptrInt = &sample;ptrVoid = (void *)(ptrInt);ptrChar = (char *)(ptrVoid);/*manipulating ptrChar */for (indx = 0; indx < 4; indx++){printf (“\n Value: %x \t Address: %p”, *(ptrChar + indx), ( ptrChar + indx)); }Output:Value: 00000078 Address: 0022FF74Value: 00000056 Address: 0022FF75Value: 00000034 Address: 0022FF76Value: 00000012 Address: 0022FF77Question: Why
Frion3L
c++ inheritance downcasting
I have a doubt about downcasting an object in C++.Here it comes an example:class A { } class B : public A { public:void SetVal(int i) { _v = i; }private:int _v; }A* a = new A(); B* b = dynamic_cast<B*>(a); b->SetVal(2);What would it happen with this example? We are modifying a base clase like if it is a child one… how does it work related with the memory? With this cast… Is it like creating an instance of B and copying the values of A?Thanks
Web site is in building