Reputation: 75
So I have a dynamically allocated array of base class. I've stored a few objects of its derived class inside the array.
The student (base) class and its derived classes all have a getInfo()
function, obviously the derived classes have overrided that base getInfo()
. The goal is to used the getinfo
function from the base class, then type class the two objects of the derived class, back into the derived class and use the overrided getinfo()
.
Everything up to "break" works perfect. It's figuring out how to type cast the objects back into the derived classes that's killing me.
I've identified a few possible issues:
1) I didnt dynamically allocate correctly. Very possible because I hate pointers and very much suck at them.
2) I have no idea what Im doing with regard to actually type casting.
A few things of note:
1) The base class getinfo is not virtual
2) I am not allowed to modify the base class.
So, saviors of confusing code. What say you? Can you help this poor student out?
EDIT!!!
Updated code, now getting "Static_cast from Student ** to Gradstudent * is 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;
}
Upvotes: 4
Views: 6344
Reputation: 31952
dynamic_cast
returns the casted pointer, it does not modify 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 fails to cast dynamic_cast
will return nullptr
, you need to check for this to prevent a crash.
EDIT: Major Object slicing bug in your code - #1 is almost right
int arraySize = 3;
Student *classRoom;
classRoom = new Student[arraySize];
GradStudent gst1("Ta", "Da", 4444, 'A', "Death");
...
classRoom[0] = gst1;
Should be
int arraySize = 3;
Student **classRoom;
// ^
classRoom = new Student*[arraySize];
// ^
GradStudent gst1("Ta", "Da", 4444, 'A', "Death");
classRoom[0] = &gst1;
// ^
Or just
Student* classRoom[3];
GradStudent gst1("Ta", "Da", 4444, 'A', "Death");
...
classRoom[0] = gst1;
Without this, all data belonging to the derived class is lost, and the base class data alone is stored, this is called Object Slicing.
Upvotes: 6
Reputation: 2862
For polymorphism to work you need to use pointers to objects. When you do
classRoom[1] = gst1;
C++ is storing the Student part of the GradStudent object in classRoom[1].
Upvotes: 0