I'm trying to learn C++,
and I thought I'd start by exploring classes,
so I wrote this:

#include<iostream>
#include<string>

using namespace std;

class user {
	public:
		string logonName;
		string firstName;
		string lastName;
		int uID;
};


int main(){

user users[2];
int i;

users[0].logonName = "rawrMander";
users[0].firstName = "Rawr";
users[0].lastName = "Mander";
users[0].uID = 0;

users[1].logonName = "nobody";
users[1].firstName = "Nothing";
users[1].lastName = "McNothingson";
users[1].uID = 1;

users[2].logonName = "beak";
users[2].firstName = "Beaky";
users[2].lastName = "McBeakerson";
users[2].uID = 2;

for(i=0;i<=3;i++){
	cout<< 
	users[i].uID<< " -- "<<
	users[i].logonName<< ": "<<
	users[i].firstName<< " "<<
	users[i].lastName<< "\n\n";
}

return 0;

}

it compiles fine (with g++, windows port) but when I try to execute it, Windows tells me that it has encountered an error and needs to close.
What have I overlooked here?

Just to be clear.

The problem is that you have allocated an array as user users[2]; . This gives you two user objects. They can be referenced as users[0] and users[1].


When you start doing users[2].logonName; etc, you
have corrupted the memory of your program and what happens next is pure chance and unpredictable. (and normally bad!).

So increase your array to size 3, and then fix the loop which needs to be for(i=0;i<3;i++) Don't feel too bad, as always, when anyone starts on classes they seem to overlook the simple stuff for a while. [It will come back to you in a bit.]

oh, I thought users[2] meant I got from [0] to [2].
As for the loop, I last-second changed the code before posting and forgot to change the for loop.
but thanks for your help! The program works now and I'll keep an eye on that in the future.

And you'll probably here back from me more as I struggle

Glad you got it fixed, just remember the number is the amount of array slots you get starting from 0...not what you get upto and including

ps mark as solved
thanks,
Chris

WTF, I went into your program and changed the 2 to a three and my computer started beeping about 3 times a second and printing off weird symbols on the console, i nearly messed myself

When you start doing users[2].logonName; etc, you have corrupted the memory of your program and what happens next is pure chance and unpredictable. (and normally bad!).

I suppose he was right about the unpredictable part haha.

Edited 3 Years Ago by Reverend Jim: Fixed formatting

WTF, I went into your program and changed the 2 to a three and my computer started beeping about 3 times a second and printing off weird symbols on the console, i nearly messed myself

Thats because his loop still counts to 4 :P

This question has already been answered. Start a new discussion instead.