0

I want to create in C++ an array which can hold objects of diffrent classes.

It's a part of my hometask and one of the conditions is that i can't use Stl, Boost & etc.

3
  • 2
    This is a Question & Answer site, and you are a bit low on Question. Commented Feb 19, 2012 at 19:30
  • Taken literally this is impossible, as an array by definition can only ever be an array of objects of one fixed type. Commented Feb 19, 2012 at 19:54
  • What lesson have you been taught in relation to this homework? It's unusual to hold different classes of object as you can't handle them uniformly, unless you're using inheritance or templates? Is that what you're learning about? Commented Feb 19, 2012 at 21:36

3 Answers 3

1

You should create Base class and derive your class from Base class. And as a result you can create array Base* array and put there all derived classes.

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

Comments

1

You could store pointers to void* in your array and cast your objects to void*. But you should not do this!

If possible you should derive all your objects from a Base Class and store pointers to Base*. This is the better way to solve this problem.

Comments

0

Does the same container have to hold objects of the same type at the same time? If so, does it have to be able to hold any type? If so, your only solution is to use void* and store pointers to the objects you want to store.

If one container only has to hold one type of object, then you can do this using templates. If the same container has to hold different types of objects but you can place restrictions on the types it can hold, then you can make a requirement be that it derive from some Base class, and make an array of Base*.

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.