Convert Base Class to Derived Class

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

Unable to cast base class to derived class

In Case two you have an instance of dog and animal

Animal a = new Animal();
Dog d = new Dog();

Then you have reference copy of dog to animal

a = d;

So the a is points to d and d is a dog instance and instance properties like noOfTail is still exist but is hidden and not available in object a.
and then you have this line :

d = (Dog)a;

In last line you have reference copy of d to a ,so d is point to where a is point to so everything is okay.

but in case one you want copy one Instance of child class Dog to an instance of Animal so the properties of child class will be lost. you need to confirm that with Compiler and say to him you know instance properties like noOfTail will not be available any more
your code most be like this :

 Animal a = new Animal();
Dog d = new Dog();
d = (a as Dog);

Convert a base class to a derived class

This happens because BaseClass is not an instance of DerivedClass (but DerivedClass is an instance of BaseClass), so you cannot cast an instance of the base class as an instance of the derived class (well, you can, but it will be null as you have found).

You can do what (I think) you are trying to achieve by adding a constructor to the derived class that takes in the base class as a parameter:

public DerivedClass(BaseClass baseClass) {
// Populate common properties, call other derived class constructor, or call base constructor
}

Then:

 DerivedClass dc = new DerivedClass(MethodThatReturnsBaseClassObject());

Convert List of Base Class to a List of Derived Class - possible?

Cast<T> method applies cast operation to all elements of the input sequence. It works only if you can do the following to each element of the sequence without causing an exception:

ParentClass p = ...
ChildClass c = (ChildClass)p;

This will not work unless p is assigned an instance of ChildClass or one of its subclasses. It appears that in your case the data returned from the server API contains objects of ParentClass or one of its subclasses other than ChildClass.

You can fix this problem by constructing ChildClass instances, assuming that you have enough information from the server:

List<ChildClass> childList = parentList
.Select(parent => new ChildClass(parent.Name, ... /* the remaining fields */))
.ToList();

Python inheritance: convert from Base class to Derived class

Python cannot cast an object to another class (even subclass).

You must use concrete class when you create the game object. It can be done in a factory method (e.g. create_game), like this:

def create_game(online_game):
if online_game.type == 'baseball':
return BaseballGame()
else:
return Game()

def fetch_game_data:
games = []
games_found_online = code_that_fetches_online_games
for online_game in games_found_online:
new_game = create_game(online_game)
new_game.home_team = ...
new_game.away_team = ...
games.append(new_game)
return games

C++ cast to derived class

Think like this:

class Animal { /* Some virtual members */ };
class Dog: public Animal {};
class Cat: public Animal {};

Dog dog;
Cat cat;
Animal& AnimalRef1 = dog; // Notice no cast required. (Dogs and cats are animals).
Animal& AnimalRef2 = cat;
Animal* AnimalPtr1 = &dog;
Animal* AnimlaPtr2 = &cat;

Cat& catRef1 = dynamic_cast<Cat&>(AnimalRef1); // Throws an exception AnimalRef1 is a dog
Cat* catPtr1 = dynamic_cast<Cat*>(AnimalPtr1); // Returns NULL AnimalPtr1 is a dog
Cat& catRef2 = dynamic_cast<Cat&>(AnimalRef2); // Works
Cat* catPtr2 = dynamic_cast<Cat*>(AnimalPtr2); // Works

// This on the other hand makes no sense
// An animal object is not a cat. Therefore it can not be treated like a Cat.
Animal a;
Cat& catRef1 = dynamic_cast<Cat&>(a); // Throws an exception Its not a CAT
Cat* catPtr1 = dynamic_cast<Cat*>(&a); // Returns NULL Its not a CAT.

Now looking back at your first statement:

Animal   animal = cat;    // This works. But it slices the cat part out and just
// assigns the animal part of the object.
Cat bigCat = animal; // Makes no sense.
// An animal is not a cat!!!!!
Dog bigDog = bigCat; // A cat is not a dog !!!!

You should very rarely ever need to use dynamic cast.

This is why we have virtual methods:

void makeNoise(Animal& animal)
{
animal.DoNoiseMake();
}

Dog dog;
Cat cat;
Duck duck;
Chicken chicken;

makeNoise(dog);
makeNoise(cat);
makeNoise(duck);
makeNoise(chicken);

The only reason I can think of is if you stored your object in a base class container:

std::vector<Animal*>  barnYard;
barnYard.push_back(&dog);
barnYard.push_back(&cat);
barnYard.push_back(&duck);
barnYard.push_back(&chicken);

Dog* dog = dynamic_cast<Dog*>(barnYard[1]); // Note: NULL as this was the cat.

But if you need to cast particular objects back to Dogs then there is a fundamental problem in your design. You should be accessing properties via the virtual methods.

barnYard[1]->DoNoiseMake();


Related Topics



Leave a reply



Submit