Search code examples
classstlconstructordestructorsuperclass

iterating through a vector that takes in class's


The following are 3 parts of my current code. I get an error in my main.cpp file when i try to iterate through my vector and dereference to the "compare" method. Can someone help me figure out what is causing this error?

Main.cpp:

#include <iostream>
#include <vector>
#include "Scores.h"

using namespace std;

int main()
{
    vector<comparable*> comparables;

    for(int i = 0; i < 5; i++)
    {
        comparables.push_back(new Player());
    }

    for(vector<comparable*>::iterator itr = comparables.begin(), end = comparables.end(); itr != end ; itr++ )
    {
        (itr*)->compare(); ****THIS IS THE LINE WHERE THE ERROR OCCURS****************
    }

    cout << "Mission Accomplished!\n\n";

    return 0;
}

I get the error of : error: expected primary-expression before ')' token. and I cant figure it out. Btw this is what the changed code looks like.

Scores.cpp:

#include <iostream>
#include "Scores.h"
#include <string>

using namespace std;

void Player::compare()
{
    cout << "comparing" << '\n';
}

Player::Player()
{
   getname();
   getscore();
}

void Player::getscore()
{
    cout << "Enter score: ";
    cin >> player_score;
}

void Player::getname()
{
    cout << "Enter Name: ";
    cin >> player_name;
}

Header file (Scores.h)

#ifndef SCORES_H_INCLUDED
#define SCORES_H_INCLUDED

class comparable
{
    public:

    virtual void compare() = 0;

};

class Player: public comparable
{
    public:

    Player();
    void compare();
    void getscore();
    void getname();

    private:
    std::string player_name;
    int player_score;
};


#endif // SCORES_H_INCLUDED

Solution

  • What about replacing

    for(vector<comparable*>::iterator itr = comparables.begin(), end = comparables.end(); itr != end ; itr++ )
    {
        (itr*)->compare(); ****THIS IS THE LINE WHERE THE ERROR OCCURS****************
    }
    

    by

    for(vector<comparable*>::iterator itr = comparables.begin(), end = comparables.end(); itr != end ; itr++ )
    {
        (*itr)->compare(); // THIS WAS THE LINE WHERE THE ERROR USED TO OCCUR :)
    }