C ++ Type of base fill object on derived object

So, I have a dynamically allocated array of a base class. I saved several objects of my derived class inside an array.

The student (base) class and its derived classes have the getInfo() function, obviously, derived classes have redefined this getInfo() base. The goal is to use the getinfo function from the base class, then enter the class two objects of the derived class, back into the derived class and use the overridden getInfo() .

Everything you need for a break works fine. He figures out how to inject objects back into derived classes that are killing me.

I identified several possible problems:

1) I did not dynamically distribute correctly. Very possible because I hate pointers and really suck them.

2) I have no idea what I am doing with regard to type casting itself.

A few notes:

1) The getinfo base class is not virtual

2) I am not allowed to change the base class.

So, the saviors of the confusing code. What do you say? Can you help this poor student?

CHANGE !!!

Updated code, now getting "Static_cast from Student ** to Gradstudent * not allowed"

 #include <iostream> #include "GradStudent.h" #include "UndergradStudent.h" int main() { int arraySize = 3; Student* classRoom[arraySize]; GradStudent gst1("Ta", "Da", 4444, 'A', "Death"); cout << gst1; UndergradStudent ust1("Bluh", "Bluh", 2222, 1); cout << ust1; Student bst1( "Blah", "Blah", 1111 ); classRoom[0] = &bst1; classRoom[1] = &gst1; classRoom[2] = &ust1; for (int x = 0; x < arraySize; x++) { cout << classRoom[x]->getInfo(); cout << endl; } cout << "TEST" << endl; GradStudent* gStudent = static_cast<GradStudent*>(&classRoom[2]); cout << gStudent->getInfo(); return 0; } 
+4
source share
2 answers

dynamic_cast returns a cast pointer; it does not change the parameter itself.

You need to do something like below.

 // removed the & since the elements are now pointers GradStudent* gStudent = dynamic_cast<GradStudent*>(classRoom[1]); cout << gStudent->getInfo(); 

Caveat - for pointers, if it cannot use dynamic_cast , will return nullptr , you need to check this to prevent a crash.

EDIT: Major Trimming objects in your code - # 1 almost to the right

 int arraySize = 3; Student *classRoom; classRoom = new Student[arraySize]; GradStudent gst1("Ta", "Da", 4444, 'A', "Death"); ... classRoom[0] = gst1; 

Must be

 int arraySize = 3; Student **classRoom; // ^ classRoom = new Student*[arraySize]; // ^ GradStudent gst1("Ta", "Da", 4444, 'A', "Death"); classRoom[0] = &gst1; // ^ 

Or simply

 Student* classRoom[3]; GradStudent gst1("Ta", "Da", 4444, 'A', "Death"); ... classRoom[0] = gst1; 

Without this, all data belonging to the derived class will be lost, and the data of the base class will be saved, this is called Trimming objects .

+6
source

For polymorphism to work, you need to use pointers to objects. When you do

 classRoom[1] = gst1; 

C ++ stores the student part of the GradStudent object in classRoom [1].

0
source

All Articles