okay so I want to check through an array of objects to see if it exists for a certain name supplied, if it exists return the appropiate object and if not i want to return NULL:
teamList is an arry of Team objects.
Team has a function called getTeamName, which returns the name of the team.
Team getTeamByName(char *name)
{
if(teamList[i].getTeamName()==name)
{
retrun teamList[i];
}
else
{
return NULL;
}
}
int main()
{
TeamList teams;
Team t1;
t1.setName("My Team");
teams.addTeam(t1);
t2=teams.getTeamByName("some name");
//now here i want to check if t2 is NULL or not,but the program crashes....
if(t2==NULL)
{
cout<<"no match"<<endl;
}
else{
cout<<t2.getTeamName()<<endl;
}
return 0;
}
is there a way to do this type of checking or something similar?
To do that, you'd need to:
1. Overload Team::Team() to take a pointer or an integer. NULL is a macro that expands to 0, so the language can interpret it either as a null pointer, or as the integer zero. If you're going to take a pointer, it's probably best to make the type one that can't be passed by the user. For example:
1 2 3 4 5
class Team{
struct placeholder{}; //Private type. Can't be used outside the class.
public:
Team(placeholder *);
};
The constructor should mark the object as invalid, possibly by setting an internal variable.
2. Overload operator==() to take the same type the overloaded constructor takes. This overload will simply return whether the object is valid.