Search code examples
c++arraysargument-passingdynamic-arraysdynamic-allocation

Getting Error when trying to pass an array of object to a function


I am trying to pass an array of Student

into the function processStudent(string myFilename, Student* myArray, int &mySize). But it is giving me different kind of errors.

The Student() does nothing, but I tried to assign them some sort of value, it still give the exact same error message:

In the main I have this:

// Create an array of students, with the size of theMax (256)
Student* arrayOfStudent= new Student[theMax];

// An integer that will keep track of actually how many students
// Because when we loop, we want to loop within the cell
// that actually have data or student.
int actualSize = 0;

// Invoke the helper function to set up the array of students
// It passed the arryOfStudent by reference, so the changes
// inside of the function will be reflected when it returns
processStudent(filename, arrayOfStudent, actualSize);

The function is like this:

void processStudent(string myFilename, Student* myArray, int& mySize)
{
    // Something here, but removed still gives that error
}

// In the class Student's cpp file

Student::Student() 
{
    // Nothing here
}

Error Message:

new-host-2:csci135p1 george$ g++ -Wall -o csci135p2main csci135p2main.cpp
Undefined symbols for architecture x86_64:
  "Student::Student()", referenced from:
      _main in cc3fTXti.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

I have been stripping and stripping down my code, but this error just won't go away. I want to create this array, and pass it to the processStudent function, so it can set up each one when reading the file.


Solution

  • You should ask yourself some questions that could help you:

    "How do I create new instance of Student?"
    Well, I do it like this: Student* s = new Student(); - it creates new object and stores the referrence to it as a pointer (Student*)

    "So how do I create an array of 10 Students?"
    Well, it's probably going to be an array of pointers to new Students and I will probably have to call new more than once... by thinking this way you would easily end up with something like this:

    Student** students = new Student*[10];
    for (int i = 0; i < 10; ++i)
        students[i] = new Student();
    

    ... which means, that when you clean it up, you will have to call delete on every Student* plus you'll have to clean up the array itself: call delete[] on Student** - and when you realize the ugly memory management connect with array of pointers, it should make you look for simpler and better ways of implementing it, thus you should end up using std::vector instead of array, objects instead of pointers if it's possible and if it's not, then use smart pointers rather than naked pointers at least.