I'm probably going to confuse myself while writing this, sorry in advance:
Is there a way I can access a location in a dynamic array(increment an array pointer) of pointers using the sizeof()
the object that is in the array?
For example: I have an dynamic array of type base class Student populated with derived class objects(Graduate, Undergraduate).
Due to this I can't just step through my array in the normal fashion to display information because the actual objects Graduate and Undergraduate are different sizes than Student. Each array step will move sizeof(Student)
when the actual objects are larger.
Depending on the type of student I am doing(this is for Graduate):
Student *student = new Graduate(undergrad, fName, lName, major, idNum, arr2, cSize,
degreeType, thesis);
arr[i] = student;
Where arr
was declared: Student *arr = new Student[size];
Using my array I had created this in a for loop:
if (!students[i].getGradStatus()){
handleGraduate(&students[i], i);
step = step + sizeof(Graduate);
}
else if (students[i].getGradStatus()){
handleUndergraduate(&students[i], i);
step = step + sizeof(Undergraduate);
}
I was trying to come up with a way to change the step size. I don't think this will work with a for loop but a while loop may be different. Pretty much I'm trying to go something similar to a file seekg()
but manually on an array.
And as I've noticed everyone likes to question the use of dynamic arrays over vectors so let me just say I cannot use vectors on this project(No STL is allowed :( ). And I have to use Polymorphism, thus why I have an array pointer of type Student holding derived class objects.
You can't store different sized objects in an array like that. When you try to copy a derived type like Graduate
over a base type like Student
you get what's known as slicing because of the differences in object size (parts can get chopped off).
To do this you need to store Student*
(pointers to Students
.)
class Student
{
std::string name;
public:
Student(const std::string& name): name(name) {}
virtual ~Student() {} // virtual destructor
virtual void handle() = 0; // implementation must override this
std::string get_name() const { return name; }
};
class Graduate
: public Student
{
public:
Graduate(const std::string& name): Student(name) {}
virtual void handle() { std::cout << "Handling Graduate" << '\n'; }
};
class UnderGraduate
: public Student
{
public:
UnderGraduate(const std::string& name): Student(name) {}
virtual void handle() { std::cout << "Handling UnderGraduate" << '\n'; }
};
int main()
{
Student** students = new Student*[3];
students[0] = new Graduate("Wendy");
students[1] = new UnderGraduate("Bob");
students[2] = new Graduate("Rachel");
for(int i = 0; i < 3; ++i)
{
std::cout << students[i]->get_name() << '\n';
students[i]->handle(); // polymorphic function (virtual)
}
delete[] students; // clean up or (better) use a smart pointer
}
Output:
Wendy
Handling Graduate
Bob
Handling UnderGraduate
Rachel
Handling Graduate