Search code examples
c++classdynamiccreation

Dynamic class creation in C++


I've this little program, and I need to create Class object dynamically. See comments below.

#include <conio.h>

#include "student.h"
#include "teacher.h"

int main() {
  short choose;

  do {

    std::cout << "\n1 - Insert student";
    std::cout << "\n2 - Insert teacher";
    std::cout << "\n3 - Show students";
    std::cout << "\n4 - Show teachers";
    std::cout << "\n5 - Exit";
    std::cout << "\n--> ";
    std::cin  >> choose;

    Student *students;

    switch (choose) {
    case 1 :
      // When user choose option 1, I would like to create
      // a new object "Student", so...
      students = new Student();
      // But if user choose 1 another time, how I create
      // another object "Student" ?
      // Could I do something like this?
      //  students = new Student[student_counter];
      break;
    }

  } while (choose != 5);

  system("pause");
  return 0;
}

Student class has a constructor. Thank you. If something is required just tell me.


Solution

  • Just use a std::vector<Student>. There's no need for dynamic allocation at all:

    std::vector<Student> students;
    
    do {
      switch (choose) {
        case 1 :
          students.push_back(Student());
          break;
      }
    }while(...)
    

    If you need to use dynamic allocation, as in it was part of the assignment, just use a std::vector<Student*> and students.push_back(new Student). You'll have to manually free the memory afterwards.