downcast

Cast the current object ($this) to a descendent class

馋奶兔 提交于 2019-11-26 09:58:16
问题 I have a class where it may be necessary to change the object to a descendent class further down the line. Is this possible? I know that one option is to return a copy of it but using the child class instead, but it\'d be nice to actually modify the current object... so: class myClass { protected $var; function myMethod() { // function which changes the class of this object recast(myChildClass); } } class myChildClass extends myClass { } $obj = new myClass(); $obj->myMethod(); get_class_name(

Why can't static_cast be used to down-cast when virtual inheritance is involved?

蹲街弑〆低调 提交于 2019-11-26 09:36:34
问题 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? 回答1: The technical problem is that there's no way to work out from a Base* what the

downcast and upcast

大憨熊 提交于 2019-11-26 08:04:02
问题 I am new to C# (and OOP ). When I have some code like the following: class Employee { // some code } class Manager : Employee { //some code } Question 1 : If I have other code that does this: Manager mgr = new Manager(); Employee emp = (Employee)mgr; Here Employee is a Manager , but when I cast it like that to an Employee it means I am upcasting it? Question 2 : When I have several Employee class objects and some but not all of them are Manager \'s, how can I downcast them where possible? 回答1

What is the difference between up-casting and down-casting with respect to class variable

浪尽此生 提交于 2019-11-25 23:32:57
问题 What is the difference between up-casting and down-casting with respect to class variable? For example in the following program class Animal contains only one method but Dog class contains two methods, then how we cast the Dog variable to the Animal Variable. If casting is done then how can we call the Dog\'s another method with Animal\'s variable. class Animal { public void callme() { System.out.println(\"In callme of Animal\"); } } class Dog extends Animal { public void callme() { System