0

I have a student class that contains name and id as attributes. I will add them to vector list and when iterating over the list I want to call the info method for every object. Take a look at this code:

#include <iostream>
#include <vector>
#include <string>
#include <iterator>

using namespace std;

class Student{

    string _name;
    int _id;

public:
    Student(string name, int id){
        _name = name;
        _id = id;
    }

    void info(){
        cout << _name << endl;
        cout << _id << endl;
    }

    friend ostream& operator << (ostream& c,Student &org){
        cout << org._name << endl;
        cout << org._id << endl;

        return c;
    }
};

int main(){

    vector<Student*> lista;

    Student *c1 = new Student("Nihad", 1);
    Student *c2 = new Student("Ensar", 2);
    Student *c3 = new Student("Amir", 3);
    Student *c4 = new Student("Amar", 4);

    lista.push_back(c1);
    lista.push_back(c2);
    lista.push_back(c3);
    lista.push_back(c4);

    for (vector<Student*>::iterator it = lista.begin(); it != lista.end(); it++){
        // calls operator << and prints 4 objects.
        cout << **it << endl;

        // how do I call info() with it?
        *it->info(); // does not work. (exspresion mush have pointer to class type)
    }

    system("pause");
}

I also defined operator << and as I have commented in code it works fine after double dereferencing. When I try to dereference it to get pointer to object I cannot call the info() via '->' which seems weird. What am I missing here?

nhrnjic6
  • 171
  • 1
  • 1
  • 9

0 Answers0