Menu

[solved]-C Cast Pointers Properly Let S Say Four Classes Baseclass Derivedclass1 Derivedclass2 Clas Q39044265

C++

How do I cast pointers properly?

Let’s say I have four classes, baseClass, derivedClass1,derivedClass2, and class4 that holds an array with objects ofderivedClass1 and derivedClass2.

The declaration in class4:

baseClass **pointers = nullptr;

in the constructor of class4 I create an array with pointers,based on an integer named size:

pointers = new baseClass *[size];

for (int i = 0; i < size; i++)
pointers[i] = nullptr;

Now I try to add information to on element of the array, eitherderivedClass1 or derivedClass2, example for derivedClass 1:

derivedClass1 temp; //declared a temporary object

– Write all the data into temp data members

From here on my program will always crash:

pointers[i] = new derivedClass1;

*((derivedClass1*)pointers[i]) = temp;

Any idea what is going wrong there?

Thanks!

Expert Answer


Answer to C++ How do I cast pointers properly? Let’s say I have four classes, baseClass, derivedClass1, derivedClass2, and class4 … . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *