User Tools

Site Tools


Passing Vectors of Object Pointers in C++

Learning to use vectors in c++ is fairly straight forward. But passing the collection to a function and returning an instance is not demonstrated as often.

The following code snippet should show a nice complete flow in one shot. Take a look:

#include <iostream>
#include <vector>
using namespace std;
class Planet {
        int id;
        Planet(int num){
            id = num;
class PlanetScanner {
        Planet* SelectPlanet(vector<Planet*> p){
int main(){
    Planet *mars = new Planet(1);
    Planet *earth = new Planet(2);
    Planet *venus = new Planet(3);
    vector<Planet*> planets;
    PlanetScanner *scanner = new PlanetScanner();
    Planet *selectedPlanet = scanner->SelectPlanet(planets);
    cout << "ID: " << selectedPlanet->id;
    return 1;

Everything above: the classes, the functions and everything is in one file. Structure really isn't the point here.

Start by including the vector library and ensuring the namespace of std is used. That way we can write vector instead of std::vector, but either is fine.

Next, a simple Planet class that simply holds an id variable and can be set with the class constructor. The class itself isn't that important.

Going to skip the SelectPlanet function in the PlanetScanner class for a second and talk about the main function.

In main, three Planet pointers are created with Planet instances.

Next, a vector containing Planet* pointers is created rather than a vector containing Planet instances.

Each of the three Planet pointers is pushed into the vector.

Now we can talk about the SelectPlanet function in the PlanetScanner class. I have created the class to handle the processing and returning of a planet simply to make the scope of returning an object safe.

The SelectPlanet function accepts a vector of Planet* pointers. It also returns a single Planet* pointer as opposed to returning a Planet instance.

The Planet pointer from index 1 of the vector is returned to the caller in main.

A new instance of Planet* is declared and address of the returned pointer is used.

And finally to demonstrate use, the id variable from the planet instance is printed.

vectors_of_objects.txt ยท Last modified: 2021/02/02 01:24 (external edit)