0

I have trouble figuring out how to access bject method through array of pointers to objects.

I have an env object of Environment class:

Environment env;

My Environment has some object pointers as well as a dynamic array of pointers:

    static Robot *robot;
    static Obstacle *obstacle;
    static Object **objects;

So inside objects I can have robots and obstacles:

But now when I want to access a method of an object in the objects array, how can I do that? I tried

    Environment env;
    Robot *robot;

    robot = env.objects[0];
    robot->setSpeed(175);

But it didn't work. I got an error:

error: invalid conversion from ‘Object*’ to ‘Robot*’

What am I doing wrong?

PS: Robot inherits from Object.

Thank you in advance!

1
  • 1
    Does Robot inherit from Object? Commented Nov 3, 2012 at 20:04

6 Answers 6

4

Since Robot inherits from Object you have to use either static_cast or dynamic_cast to cast the pointer:

robot = static_cast<Robot*>(Environment::objects[0]);

As a side note, I also recommend you to use std::vector instead of the array, and a smart pointer like std::shared_ptr instead of the raw pointers.

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

Comments

2

You need to cast the Object* to a Robot*. Assuming Robot inherits from Object. I advise you to use dynamic_cast:

Robot* robot = dynamic_cast<Robot*>(env.objects[0]);
if (robot != NULL) {
    robot->setSpeed(14);
}

Comments

1

You should cast your object from Object* to Robot*. However, you have to make sure it is a Robot object otherwise your application will crash.

Here is an example:

#include <iostream>
class Object
{
};

class Robot : public Object
{
  public:
  int speed;
  void setSpeed(int newSpeed){ speed = newSpeed; }
};

int main()
{
  Object* obj = new Robot();
  ((Robot*)obj)->setSpeed(4);
  std::cout << "Speed is: " << ((Robot*)obj)->speed << std::endl;
}

Comments

1

You can't implicitly assign pointer of base class to pointer of derived class. If you need to do this, use dynamic_cast.

Comments

1

objects is declared with type Object**, which means that objects[0] is of type Object*. You cannot assign an Object* to a Robot*. Assuming Robot is a class derived from Object and has at least one virtual member function, you can do

robot = dynamic_cast<Robot*>(object[0]);

This will perform the cast, or set robot to the null pointer value if object[0] happens to not be a Robot. If you know for certain that it is a Robot, you can use static_cast() instead.

Comments

0

your object does not seem to be a Robot* or a pointer to a subclass of it.

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.