Question about classes

In the following code I have the constructor which saves certain values to the class variables. I've read how to do this in the past but can't for the life of me remember where. Does anyone know how to save a class variable and class method argument with the same name?

Thanks in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
class Student
{
	public:
		char firstName[20];
		char surname[30];
		short year;
		Student::Student(char * firstName,char * surname,short year)
		{
			firstName = firstName;
			surname = surname;
			year = year;
		}
}
You can't have parameters that have the same name as your class variables, so you either have to name your parameters differently or use the "this" pointer as in:

1
2
3

strncpy( this->firstName , firstName, sizeof( this->firstName ) - 1 );


Also, please add code to check for NULL pointers!
pass in std::strings rather than char*s then you wont need to check for null pointers
+1 to quirkyusername

if you want a variable to hold a string, use a std::string.

char arrays are hard to use, restrictive, problematic, and error prone.
Last edited on
Topic archived. No new replies allowed.