Hello,
i where making a game, and i needed a vector that holds class objects, i do the thing (below), and i thing i did it right, but it seems not and i dont know whats wrong :(

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

using namespace std;

class Races {
public:

string raceName;

Races(string get_raceName);

};

vector<Races*> race_list;

Races::Races(string get_raceName) {
raceName = get_raceName;
race_list.push_back(this);
}

Races vampire("Vampire");
Races orc("Orc");
Races elf("Elf");

int main() {

Races* theRace;
int listNumber;

for (int member = 0; member < race_list.size(); ++member) {

theRace = race_list[member];

cout<< listNumber << ". " << theRace.raceName << endl;

++listNumber;

}

}

this code generates error: request for member 'raceName' in 'theRace', which is of non-class type 'Races*'

i would be greatful if someone tell me whats wrong ;)

Why are you using Races as a pointer?

You should format your code, it's hard to read.

Well if Races wouldin't be a pointer compiler would generate an error

And those errors would be?

Firstly the error in your code is due to this.

cout<< listNumber << ". " << theRace.raceName << endl;

Basically in which here is the trouble

theRace.raceName

the variable theRace is a pointer-type so the . operator cannot be used to reference its members instead -> should be used.

theRace->raceName

which is actually

cout<< listNumber << ". " << theRace->raceName << endl;

Secondly,

Well if Races wouldin't be a pointer compiler would generate an error

This is not true , There is a small mistake that you are doing which is leading for the declaration of the vector as a pointer.

For example try this out

vector<Races> race_list; //Removed the * 

Races::Races(string get_raceName) {
raceName = get_raceName;
race_list.push_back(*this); //Added the * here, Now the total member is returned. 
}

By the way , If you correct your code using the second way , the first method becomes absolutely un-necessary.

And those errors would be?

In constructor 'Races::Races(std::string)':
error: no matching function for call to 'std::vector<Races, std::allocator<Races> >::push_back(Races* const)'
In function 'int main()':
error: cannot convert 'Races' to 'Races*' in assignment
error: request for member 'raceName' in 'theRace', which is of non-class type 'Races*'

Pauliuw, Check out my previous post.

Thanks Sky Diploma :) works great :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.