I'm having difficulties understanding the following code:
class Base{
Base(){/* do stuff */};
};
class Deriv: public Base{
Deriv(){/* do stuff */};
};
// I have a problem understanding the purpose of the next line
Base &foo = *(new Deriv());
I'm having difficulties understanding the following code:
class Base{
Base(){/* do stuff */};
};
class Deriv: public Base{
Deriv(){/* do stuff */};
};
// I have a problem understanding the purpose of the next line
Base &foo = *(new Deriv());
Copyright © 2021 Jogjafile Inc.
First, you need to be familiar with Polymorphism, references, dereferencing and temporary object behavior.
The most popular examples of this are animals. Many sources describe this topic with it.
Imagine you are creating a game, where your player has a pet.
If you put it this way, you will be able to have only Dog as pet.
In this case, you can have as pet any class that inherits from Animal.
This was just one simple example of the usage of Polymorphism.
Example:
Example:
Example:
In your case, you do the following: Allocate an object in heap and return its pointer.
Dereference that pointer
Create a reference and bind it with newly created object.
And here we start to have some problems. It is not a temporary object! Your object in heap never gets destroyed. It is a clear memory leak
I don't know why are you creating a reference. The best way is to create a pointer.
And then
And that's it.
But yes, you can also delete it like this