Automatically Call Function in Derived Class

Alright, I'm not completely sure the best way to explain what I'm trying to do, as I'm trying to wrap my head around the concept.

I'm going to use an example that's from the Unity engine, which while it's kind of C# or Java if you want, I'm hoping that the concept is feasible in C++ too.

Basically, in the Unity engine I'd notice that scripts that are made have four main functions that are called automatically. Start(), Update(), LateUpdate() and FixedUpdate().

I don't have to go somewhere and type in MyClass.Update() for each time I create a new class.

Basically what I'm getting at is that it's kind of silly to have to do something like this:

1
2
3
4
MyClass.Update();
ThisClass.Update();
ThatClass.Update();
HisClass.Update();


Is there anyway using a loop or something to through every instance of a class that inherits from a class I'll just call ParentClass, then call their respective functions?

I'm sorry for the pseudo-code, but this will probably explain it better.

1
2
3
4
for(int i = 0; i < NumOfCurentParentClasses; i++)
{
    ParentClass[i].Update();
}



I'm sorry I really wish I could explain this better, and I know I'm doing crappy job. I'm sure there's a name for this concept, I just don't know what it is.
Last edited on
I don't know Unity, but from the name alone Update() sounds like a function that's called once per frame to update the internal state of the program. This works because the engine contains a tree-like structure where each node knows to call its children's Update() methods. For example, a Screen contains a Gui and a World. The Gui contains a TimeDisplay and a HealthBar. The World contains a lot of instances of Actors and a lot of instances of Entities.

The implementation probably looks like this in Unity:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Object{
protected:
    virtual std::vector<Object> GetChildren() = 0;
    //The default implementation does nothing. Subclasses may choose to override
    //this behavior.
    virtual void Update(){}
    void SuperUpdate(){
        this->Update();
        auto children = this->GetChildren();
        for (auto &child : children)
            child.SuperUpdate();
    }
};
GetChildren() can be easily automatically implemented in the Unity runtime because .NET has reflection, which allows code to, among other things, iterate over the members of a class. C++ does not have reflection, so this implementation is suboptimal in C++.

This would be better:
1
2
3
4
5
6
class Object{
protected:
    //Subclasses should implement both their own child traversals
    //and their own state updates.
    virtual void Update() = 0;
};
Last edited on
Topic archived. No new replies allowed.