Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer and vectors in C++

I'm starting with C++ and I have a doubts:

I'm making a function which will return a vector of objects of a class MyClass.

vector<MyClass>* myMethod()

The first question is, it's correct to return a pointer?

The second question is: if I'm going to return a pointer, should I also insert pointer of MyClass object into the vector?

MyClass* object;
myVector.push_back(*object);
like image 685
Maverik Avatar asked Nov 29 '22 09:11

Maverik


1 Answers

A vector can be a vector of objects or a vector of pointers. This is completely independent of whether you have a vector or a pointer to the vector.

If you are starting out with C++ try to avoid pointers altogether. Just return a vector of objects. Remember that the vector contains its contents. When you put an object into a vector it will be copied in.

like image 110
CB Bailey Avatar answered Dec 06 '22 09:12

CB Bailey