Like in Game engines for example in XNA the update function is called automatically again and again. I want to know how i can achieve this in c++.
For ex:
class base
{
void Update();
};
class child1: public base
{
void Update();
}
class child2: public base
{
void Update();
}
void main()
{
base *obBase = new base();
obBase->Update(); /*This should call Update of Child1 and Child2 classes how can I do this*/
}
Just make it virtual:
class base
{
virtual void Update();
};
This will provide polymorphic behavior
And I assume you ment:
base *obBase = new child1(); //or new child2();
You can't access all instances of a derived classes of a base class.
What you need to do is to have some kind of a container, which will store all your objects of type Child1
and Child2
and then, when you decide, iterate through this container and call Update
.
Something like:
SomeContainer< base* > myObjects;
// fill myObjects like:
// myObjects.insert( new ChildX(...) );
// ...
// iterate through myObjects and call Update
To be able to do this, you need to make Update
a virtual function.
To prevent (potential) memory leaks, use smart pointers, instead of base*
.
I guess you are trying to use polymorphism, something like this:
Base* obj1 = new Child1();
Base* obj2 = new Child2();
BaseManager* manager = new BaseManager(); //A class with a data struct that contains instances of Base, something like: list<Base*> m_objects;
manager->add(obj1); //Add obj1 to the list "m_objects"
manager->add(obj2); //Add obj2 to the list "m_objects"
manager->updateAll(); //Executes update of each instance in the list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.