Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, vectors, pointers and objects confusion

Tags:

c++

I am working on a project as a homework for my university course of Systems Programming. I got really confused with the matter of Pointers, Vectors, stacks and heaps.

Using C++. I have to get a vector of objects which are courses, and those courses objects have several different fields. What I did was this:

vector<CoursesObject> coursevector;

and then I created my Courses Object class, which contains the space left in course and name of course fields. Now I want to add a new course, I do:

CoursesObject *theCourse = new CoursesObject(name, space);

now I want to add it to the handler vector:

coursevector.push_back(*theCourse);

With all I know, I created a vector of Courses objects on the stack, and made a new pointer to a new course that is on the heap, and added to the handler vector the pointer theCourse that points to the course object in the heap. Is what I said correct?

When I try to delete those course objects, I do:

for(int i=0; i<coursevector.size(); i++)
    delete coursevector.at(i);

which gives me an error that it is not a pointer. But haven't I added to the coursevector a POINTER to the course object?

Please somebody explain, I have to handle the memory correctly and it seems that I am not getting it right.

like image 387
TheNotMe Avatar asked Jan 16 '23 03:01

TheNotMe


2 Answers

This

vector<CoursesObject> coursevector;

is a vector of CourseObjects, so it cannot hold CourseObject pointers. When you do this:

coursevector.push_back(*theCourse);

you get a copy of the CoursesObject pointed at by theCourse stored in the vector. You do not need to delete any entries from the vector. In fact, you can't, because it doesn't hold pointers.

You program would be much simpler if you just avoided the dynamic allocation:

coursevector.push_back(CoursesObject(name, space));
like image 179
juanchopanza Avatar answered Jan 17 '23 18:01

juanchopanza


You do not need to use new at all.

//This vector stores CoursesObject objects,
//not pointers to CoursesObjects.
vector<CoursesObject> coursevector;
//Construct theCourse with automatic storage
//duration.
CoursesObject theCourse(name, space);
//Copy theCourse into coursevector
coursevector.push_back(theCourse);
//theCourse will be automatically destroyed.
//coursevector (and all the objects that it contains)
//will be automatically destroyed.
like image 23
Mankarse Avatar answered Jan 17 '23 17:01

Mankarse