0

I have two classes (TypeA, and TypeB) where TypeB extends TypeA.

If I create an object like so:

ATypeA* NewObject = SpawnObject<ATypeB>();

the Spawn object method just creates a new ATypeB object

and then store it in an array of TypeA, is the object within the array of TypeA or TypeB?

3
  • it will be from TypeA Commented Jun 21, 2016 at 11:03
  • Do you store the object or the pointer in the array? Commented Jun 21, 2016 at 11:04
  • You only get polymorphism with pointers and references. When you assign to a regular variable, you just get the slice with that class. Commented Jun 21, 2016 at 11:12

1 Answer 1

2

It depends on your array and how you assign the object.

If the array is declared as TypeA myArray[10]; and you assign your object using myArray[0] = *NewObject; then the object in the array will be a sliced copy of *NewObject of type TypeA.

If the array is declared as TypeA* myArray[10]; (probably your intention) and you assign your object using myArray[0] = NewObject; then the array will contain a pointer to the same object pointed by NewObject, of course of type TypeB.

That said, you should probably consider using std::vector<std::unique_ptr<TypeA>> rather than a raw array. It will make your code simpler and safer.

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.