Array of Pointers?

Started by
4 comments, last by PhiberOptic 18 years, 9 months ago
Are array of pointers to classes used mainly to avoid the overhead of copying large class objects into data structures such as arrays / vectors, or is there another reason? What other areas would it be wise to use them in?
Advertisement
Quote:Original post by Gink
What other areas would it be wise to use them in?

Inheritance. If you have some interface exposed through a base class, a container full of pointers to that base class can have objects of any derived class in them. If you store actual objects, you lose all the derived functionality.

CM
So using actual objects is equivalent to downcasting a subclass to the superclass(all data from the subclass would be gone)?
Quote:Original post by Gink
So using actual objects is equivalent to downcasting a subclass to the superclass(all data from the subclass would be gone)?


Quick example:
class Parent{public:   void IAmTheParent() { }};class Child : public Parent{   public:      void IAmTheChild() { }};Parent* ptr = new Child;ptr->IAmTheParent(); // Worksptr->IAmTheChild(); // Does not work, Child functionality removedChild* temp = (Child*)ptr; // Dangerous doing it like this, but we know ptr is of the Child classtemp->IAmTheChild(); // Works finetemp->IAmTheParent(); // Will also work because of inheritance


As for reasons to use this, I agree with CM. In a game you can have one abstract class that contains the basic functions all object should have in the game, Draw, Update, Destroy, and Create. Then you can simply make a vector of those objects and easily call the cycles of them. When you need specific objects, you can typecast based on a class ID that you can opt to add in. Neat stuff.
Quote:Original post by Drew_Benton
...

To expand on that a bit:
class Parent{public:   void IAmTheParent() { }   virtual void WhoAmI() {cout << "Parent" << endl;}};class Child : public Parent{   public:      void IAmTheChild() { }      virtual void WhoAmI() {cout << "Child" << endl;}};Parent* ptr = new Child;ptr->WhoAmI(); //outputs "Child"delete ptr;Parent parent = Child();parent.WhoAmI(); //outputs "Parent"Child child = Child();child.WhoAmI(); //outputs "Child"child = Parent(); //Compile error

The Parent object is not aware of the fact that it is supposed to be a Child. But the Parent* object is. So your question about downcasting is exactly right.

CM
Here is one gameprogramming usage:

class GeneralMonster {..};class Spider : public GeneralMonster{..};class Dragon : public GeneralMonster{..};#define numMonster 2GeneralMonster* monsters[numMonster];monsters[0] = new Spider();monsters[1] = new Dragon();for(int i=0;i<numMonster;i++){   monsters->Update();   monsters->Render();}
----------------------------------------------Petter Nordlander"There are only 10 kinds of people in the world. They who understand binary and those who do not"

This topic is closed to new replies.

Advertisement