Unreal Engine 4 Cast to parent Class Fails - casting

I want to Cast a Child to his Base Class.
I have a Class called Road_Empty and a child Class Road_Left.
Iam using this flow to spawn a Random Road Tile.
Flow
This should run smoothly. But the Cast fails evertime.
What is wrong there?

Though you've found that the reason is Classes are filled with wrong types, I'd like to provide some more information:
You don't have to cast child classes objects to parent class object, since they can be used directly as parent class object.
If your spawning failed so it returns None, the cast can also failed. The most common failure is because of collision handling, but in your case of Always Spawn, Ignore Collisions then it can hardly fails.

Related

Unreal Engine 4. Different ways to instantiate the object

I found about four different ways to instantiate the object, but not sure if my understanding is clear.
NewObject<T>() function used when we want to make at the instance of UObject. For example, it can be any ActorComponents.
USomeComponent sc = NewObject<USomeComponent> (class);
ConstructObject<T>() one more way to init UObject...
CreateDefaultSubobject<T>() but using this one function we also can create an instance of any class inherited from UObject.
SpawnActor<T>() used for instantiating an object of AActor class.
So first question: What is the difference if we can use these functions for one purpose? How and when and why we need to use any of them?
To understand the difference between these functions, you need to remember that the object model
in Unreal Engine is based on object prototypes, very much like in JavaScript. Each UClass is associated
to a default instance of the associated UObject class, called the Class Default Object (CDO), which is
allocated first and then constructed, only once, via the class constructor when the engine is initialised.
The CDO acts as a template from which all other instances of the class are copied, and the constructor is
never called again.
This means class constructors cannot contain any runtime logic, and should only be used to
initialise the CDO and its properties. If the class contains any subobjects, like actor components,
these must do the same, so their own default objects must be constructed first. The actual instantiation of
the object must then be deferred, after the engine has initialised, so that every time a new instance of the class is
requested to be created by normal gameplay code, the parent object and all of its subobjects are instantiated from their respective defaults.
So, the multiple ways of creating objects are necessary to handle all the different
scenarios where an object may be created.
UObject::CreateDefaultSubobject is only callable in a class constructor, and takes care of creating an instance of the CDO
of the subobject's class, setting its outer class as the caller object,
among other things. The created object then becomes the default object for the property when its object class is instantiated.
NewObject<T> is the function normally used to instantiate objects after engine initialisation, during normal gameplay. It
provides several convenience overloads to handle most scenarios.
UWorld::SpawnActor<T> is a convenience method to spawn actors in a level with the specified location and rotation,
spawn collision settings, and checks to ensure it's a spawnable actor class, and is nothing more than a wrapper of
NewObject<AActor>.
ConstructObject has been removed in favour of NewObject.
I recommend checking the engine source code for more information, especially UObject/UObjectGlobal.cpp
and UObject/UObjectGlobal.h in the CoreUObject engine module. Internally, all these function ultimately call (as of 4.24)
StaticConstructObject_Internal, which handles the actual object creation.

Correct design to pass generics in messages to event listeners

Please feel free to truncate this question if it is overly long.
I'm having some trouble understanding how to pass generic arguments to event listeners (e.g. callback functions) without breaking principles of OOP and polymorphism.
For the purposes of this question, assume the implementation is written in C++.
Let's say I have an animal class with two children, cat and dog.
I also have a doorbell event object which should cause dogs to speak(), but cats do not respond.
However, I have all of my animals stored polymorphically. I cannot simply call speak() on every animal, since cats should not respond.
One (bad) solution is to use dynamic casting to check each animal, and see if it's of type dog. If so, I call its speak function. If not, I don't. The issue here is that it breaks the purpose of polymorphism and virtual functions (not needing to know information about the children classes, but rather just the parent interface).
For a better solution, I might choose to use an event driven system. I'd have an event_manager, and each dog is registered as a listener to the doorbell event (possibly by some event ID, the event name, etc.) Perhaps each dog registers its callback function with the event.
Then, when the doorbell is rung, it tells the event_manager to invoke the callback functions of every listener registered to the doorbell event.
This is much better, but what if information about the target (the doorbell_ring) needs to be passed to the dogs? For example, how loud did it ring? If it was quiet, perhaps the dogs do not respond, based on their hearing capability. Perhaps if it is very loud, the dogs respond more aggressively.
The only solution is to pass the target doorbell into the event handler (dog) callback function.
Here is where I'm confused: every callback function must match the same function signature in order for it to be generically invokeable by the event_manager. While in this case the dogs need access to the information about the doorbell_ring, given any other event, the listener may need access to information about an entirely different target.
The only solution I can think of is passing the targets as void pointers and explicitly downcasting to the determined target type (e.g. the dogs, in this callback function, would downcast the target to the doorbell_ring* type).
While this would certainly work, isn't it essentially the same as the very first solution, wherein we check if an animal is of type dog via dynamic casting and, if so, invoke its response? Imagine that, instead of using dynamic casting, we give every animal a type identifier, and just check against each animals identifier. Now, we're simply casting an animal to a dog based on its identifier. In the event driven system, we're simply casting a target to the determined subtype based on the identifier of the event which invoked the callback.
In a round about way, doesn't this have the same design issues? We're simply using void pointer generics and downcasting to the correct type based on some type id instead of downcasting from the animal class to the dog class.
Is there a better design pattern?

I can't access members of a child class through functions, how do I?

Okay, so my situation is really complex to a relativity new person to C++ like me. I'm making a game (AGK library) and I have a framework class that is the base class for all of the game's objects to have standard functions like frameEvent and such that are to be overwritten by the child object.
That's all fine and dandy, and I've gotten about 70% through development, but I ran across one vital problem.
To make life easier while processing the game, each object that is a part of the game is just a pointer in a vector of type Framework*. Framework being the base class. I was told that making it a pointer allows me to have child objects of different types as long as they're a pointer as well. So far it's worked out.
Every frame, the global object runs through the vector of all the objects and runs their
frameEvent
frameEndEvent -- Can't be overriden
drawEvent
They're really just functions. So in the enemy's bullet class, I need to check if it collides with oPlayer, so I have a functions in the global class (The global class is passed to the objects in their frame event so they can communicate with other objects.) that grabs a given object.
It searches through all of the objects to find the parameter object -- so if I pass new oPlayer, it will return the real oPlayer pointer in the game.
When the bullet collides with the player, it needs to lower the player's health and then destroy itself. So at the create function for the bullet, it creates a dummy player then locates the real one using the global class function. The code is
//Find the player
oPlayer* tempPlayer = new oPlayer;
playerChecker = ObjGlobal->classToObject(tempPlayer);
tempPlayer->objectDestroy();
That code works, but it needs playerChecker to be type Framework* because that's what classToObject returns. But when I later use that pointer, I can't access the player's members even though that's the player's pointer.
playerChecker->hitPoints--;
hitPoints is exclusive to oPlayer. I think it's called object splicing or slicing, but I thought that's what using pointers fixed.
So I tried to make playerChecker type oPlayer*, but it says that Framework* can't be converted to it. So I have no idea what to do.
Any help is greatly appreciated.
Your Framework* from classToObject can be downcast to a oPlayer* using a dynamic_cast, like so:
oPlayer* playerChecker = dynamic_cast<oPlayer*>(ObjGlobal->classToObject(tempPlayer));
if (oPlayer) {
// cast succeeded, do stuff with the pointer
}
dynamic_cast is a C++ type cast operator just like the C-style cast, with some special properties. It is specifically designed to convert between pointers or references to polymorphic objects (like your oPlayer, which can be treated as both a Framework and an oPlayer). It also adds a run-time check which verifies that the object you're trying to downcast is indeed an instance of the class you're trying to cast to. If it isn't, it will return a null pointer, or in the case of references, throw an exception.
Your code will also work with a C-style cast or a static_cast (which is much like a C-style cast with compile-type type checking).
static_cast<oPlayer*>(ObjGlobal->classToObject(tempPlayer)) // static_cast
(oPlayer*)ObjGlobal->classToObject(tempPlayer) // C-style cast
These have less overhead because of the lack of a run-time check, but that also means that they are unsafe unless you can guarantee that the pointer you're casting points to an object of the correct type. Also, since dynamic_cast has a very specific use, it makes it clear what your intent is.
What's the error you're getting? Please post this, as we can't offer much help otherwise.
If I had to guess, you forgot to add public: to your class FrameWork. This, or you don't have setters/getters in your class.

How do I make destructors protected for a whole class hierarchy in a maintainable way?

I would like to make sure no one is able to delete any objects from my class hierarchy other then by using a provided Destroy method.
The rationale is that any object from this hierarchy needs to take a special write mutex before it starts to destroy itself to make sure objects are not deleted while another thread is using them.
I know I could prevent this problem with reference counting but it would be a much bigger change to the system also in terms of potential performance impact and memory allocation.
Is there a way to somehow efficiently/smartly make all the destructors protected so that child classes can call their parents destructors while outsiders have to use Destroy?
One solution that is safe (ie. it will not rot) that I came up with is to make all the destructors private and declare each derived class as a friend of the base class but I'd prefer something more elegant, less manual and easier to maintain (like not requiring to modify base classes in order to derive from them).
Is there anything like this available? Maybe some smart trick that makes things "work" as I'd like?
ps. The solution I chose for now is to NOT prevent anyone from calling delete in all cases (just made it protected in the base class) but detect this situation and call abort in the base class destructor.
Don't try to reinvent the lifetime mechanisms provided by the language.
For an object of your class to be correctly initialised it needs to also be able to clean itself up.
In its constructor pass either the mutex, or a means of obtaining a mutex, which it can use in its destructor.
Thanks for all your feedback and discussion. Yes - it proved it's impossible to do what would be my natural first choice :( (to have the "protection" of the destructor take effect in derived classes just as it's "virtuality" does).
My solution in this particular case (solving all potential problems with being able to make hones mistakes by introducing new derived classes that violate previous agreements AND keeping the solution in one place/maintainable (no code duplication in derived classes etc)) is:
Make all the existing class hierarchy destructors I can find protected
Provide a Destroy method in the base class that can be used to initiate the destruction of these objects - if called the method lights up a flag on the destructed object that it was properly destroyed and then calls delete on it
In the base class destructor (once we get to it) check the flag - if it's not set it means someone introduced a new class and called delete on it directly or avoided the compilers protection checks in some other way (abused some friendships etc) - I abort the application in this case to make sure the issue cannot be ignored/missed
I had the same needs, but for a different reason. In our company framework, nearly all classes derive from a common BaseObject class. This object uses a reference count to determine its life time. BaseObject has in particular these three methods: retain(), release() and autorelease(), heavily inspired from Objective-C language. The operator delete is only called inside release() when the retain count reaches 0. Nobody is supposed to call delete directly, and it is also undesirable to have BaseObject instances on stack.
Therefore, all our destructors should be protected or private. To enforce this, as I know it is impossible from the language, I wrote a Perl script that looks for all destructors within a source directory and makes a report. It is then relatively easy to check that the rule is respected.
I made the script public, available here: https://gist.github.com/prapin/308a7f333d6836780fd5
It can be done with help of testing. For a class with an protected destructor you need 2 test cases:
one function (in one file) which fails to compile simply creating such an object
one function (in second file) which creates an object with an derived class which compiles.
If both test cases work I think you can be sure your classes are protected as you like.
I don't know wether you are able to implement it with your build system but I have an example using bjam (from boost) at git hub. The code is simple and works for gcc and msvc. If you don't know bjam you should look inte Jamroot.jam. I think it is clear without any further comment how this simple example works.

Is there a way to scan for when people forget to call the base class version of a virtual?

I just fixed a memory leak caused by someone forgetting to call the superclass's OnUnload in their override of it. The superclass version frees some resources (as does its superclass).
Are there external static analysis tools, or at least some kind of runtime trick I can do to detect this? With the ability to make an exception obviously (though these cases are exceedingly rare).
UPDATE: Based on the answers below, I need to add constraints that are specific to our setup, which is a game for Wii/360/PS3. Very specific engine for a very specific application.
We have a deep hierarchy of game object classes (a design I never agreed with, but it's the design we are shipping). Deep and wide, actually. I am going to redo this for the next game to use a Dungeon Siege-style component-based system but in our current codebase, deep hierarchies make the DispatchVirtual() -> onVirtual() pattern difficult to apply.
Destructors do not get called for our game objects because delete doesn't get called. Game objects go into an add-only (stack) allocator-based pool during a world load. At the end of a level I just set the stack pointer back to the low water mark to free everything at once. In advance, we iterate all objects and call OnUnload on them so they can free any external resources they use. You might call it "garbage collection: the nuclear option". So no destructors.
Even if we could use a destructor-based approach it would only solve the narrow problem of an OnUnload or OnFree, but not OnUpdate, OnWorldMessage, OnLoaded, etc.
Runtime solutions are interesting but I hate relying on testing to catch this. Optimal would be either a compile-time template trick or an external static analysis tool I can use.
Don't trust the derived classes to do it; use the template method design pattern to ensure your base class behavior will always happen:
class Base
{
public:
void OnUnload()
{
// Do stuff that must always be done.
this->doOnUnload();
}
private:
// Virtual method for derived classes to override.
// Can be pure virtual if it will always be overridden.
virtual void doOnUnload()
{
// Empty default implementation
}
};
The only problem is that this only buys you one level of inheritance, and your problem says you need two. In which case, this pattern can be repeated.
But in general, it's usually more stable to have base classes call down to derived classes for specific behavior than to require derived classes to call up to base classes.
A runtime "trick" you could use is to assert in the destructor of the base class if the constraint you are looking for has failed. Assuming the instance is actually destroyed and not leaked, this will tell you at the time the object is destroyed if the contract was correctly followed.
A "runtime trick" is to wrap your resources in a class and make sure that resource class handles allocation / deallocation appropriately. A major benefit you have in C++ over 3G languages is multiple inheritance.