0

I have an array of objects whose class is a base class, and the elements of the array are derived classes.

    Object *object [kNumPlayers] =
   {
        new Human ("Ms. Jones", 50, 1.0f, 2.0f),
        new Alien ("Mx. Charm", 70),
        new Human,
        new Alien,
   };

So here, Object is the base class, and Human and Alien are derived classes. Now my problem is that I need to access each of the objects and add extra functionality. As in, I need to access object[0](which is Human) and add whatever needs to be added. So I tried,

   Human human0 = (Human)object[0]; // ERROR:'no matching function to call                  Human::Human(Object*&)'
                        OR
   Human *human0;
   human0 = dynamic_cast<Human*>(object[0]); //ERROR: cannot dynamic_cast 'object[0]' (of type 'class Oject*') to type 'class Human*' (source is not polymorphic)'
3
  • 1
    You base class needs at least one virtual function. Commented Apr 13, 2015 at 15:42
  • 1
    with raw pointers you should write Human* human0 = (Human*)object[0]; Commented Apr 13, 2015 at 16:03
  • How do I then access object[0] in Human class? If i have 2 objects say, Human* human0 = (Human*)object[0]; and Human* human1 = (Human*)object[1], then how do I say "if (object[0]) then - "This is want I want to do" Commented Apr 13, 2015 at 19:54

1 Answer 1

4

For the dynamic_cast to compile, the rule is that the source class must be polymorphic class — which means it must have at least one virtual function, even be it the destructor only. In your case, the source class is the Object class which must be polymorphic:

class Object
{
   public:
     virtual ~Object() = default; //at least, it should be virtual
     //etc
};

Once you fix that the code should at least compile. However, there are many things you should avoiding using in C++:

  • Avoid using C-style arrays (dynamic or otherwise)
    • Prefer std::vector or std::array.
  • Avoid managing memory yourself — that is, avoid using naked new.
    • Prefer RAII — in your case use std::unique_ptr or std::shared_ptr whatever suits your need.

That is you should something like this:

 std::array<std::shared_ptr<Object>, 10> objects {
        std::make_shared<Human>("Ms. Jones", 50, 1.0f, 2.0f),
        std::make_shared<Alien>("Mx. Charm", 70)
        //etc
 };

And cast as:

 std::shared_ptr<Human> human = std::dynamic_pointer_cast<Human>(objects[0]);

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.