Search code examples
c++inheritancedynamic-allocation

Dynamically allocating classes, with Inheritance issue


I am trying to dynamically allocate an array of base(Student) classes, and then assign pointers to derived(Math) classes to each array slot. I can get it to work by creating a single pointer to the base class, and then assigning that to a derived class, but when I attempt to assign to the pointer to a dynamically allocated array of base classes, it fails. I have posted the fragments of code that I am using below. So basically my question is, why isn't the dynamically allocated one working?

   Student* studentList = new Student[numStudents];  
   Math* temp = new Math(name, l, c, q, t1, t2, f);  
   studentList[0] = temp;                                 

/*Fragment Above Gives Error:

main.cpp: In function âint main()â:
main.cpp:55: error: no match for âoperator=â in â* studentList = tempâ
grades.h:13: note: candidates are: Student& Student::operator=(const Student&)*/



   Student * testptr;
   Math * temp = new Math(name, l, c, q, t1, t2, f);
   testptr = temp
   //Works

Solution

  • studentList[0] is not a pointer (i.e. a Student *), it's an object (i.e. a Student).

    It sounds a bit like what you need is an array of pointers. In which case, you should do something like:

    Student **studentList = new Student *[numStudents];
    Math *temp = new Math(name, l, c, q, t1, t2, f);
    studentList[0] = temp;
    

    In this snippet, the type of studentList is Student **. Therefore, the type of studentList[0] is Student *.

    (Note that in C++, there are better, safer ways to do this, involving container classes and smart pointers. However, that's beyond the scope of the question.)