my first attempt at writing code using classes - please help

Pages: 12
I am supposed to be using the get function that retrieves the member variable and the set function that assigns a value to the member variables.

Earlier I tried to use them instead of the cin and cout. But that didn't work.

I've looked them up in online tutorials but they are too simplified and I can't make the connection to how I need to use them in this code.

Here's my latest. Next, adding data validation...But really need to know how to use the set and get member functions...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <string>
#include<conio.h>
using namespace std;
 	
//declaration section
class Student {
      private:
              string FirstName;
              string LastName;
			  string City;
			  string State;
			  string Telephone;
			  string Year;
			  int Enrolled;			//number of credit hours currently enrolled
			  int Completed;		//number of credit hours completed prior to current semester
			  int Graduation;  		//number of credit hours needed for graduation after current semester
			
//interface
      public:
		    void getData()	//request user data input
			{
				cout << "Enter student first name: ";
				cin >> FirstName;
				cout << "Enter student last name:  ";
				cin >> LastName;
				cout << "Enter student city of residence:  ";
				cin >> City;
				cout << "Enter student state of residence:  ";
				cin >> State;
				cout << "Enter student telephone number:  ";
				cin >> Telephone;
				cout << "Enter the student credit hours currently enrolled:  ";
				cin >> Enrolled;
				cout << "Enter the student credit hours completed:  ";
				cin >> Completed;
				cout << "Input accepted" << endl;
			}
			void calcGraduation()			//total hours needed for graduation are 90
			{
				Graduation = 90 - Completed - Enrolled;		//calculate how many remaining hours required for graduation
			}	
			void displayData()		
			{
				cout << endl << "Student: " << FirstName << " " << LastName<< endl;
				cout << "Location: " << City << ", " << State << endl;
				cout << "Telephone: " << Telephone << endl;
				cout << "Currently enrolled: " << Enrolled << " credit hours" << endl;
				cout << "Hours completed: " << Completed << " credit hours" << endl;
				cout << "Credit hours required for graduation: " << Graduation << " credit hours" << endl;
			}
};


int main ()
{
	Student student[5];
	for (int i=0; i<5; i++)
	{
		student[i].getData();
		student[i].calcGraduation();
	}
	for (int i=0; i<5; i++)
		student[i].displayData();
return 0;	
}

By the way, I can't thank you enough for the time you're spending explaining this. You are very much appreciated.

edited to add: I am going to split the code into the multiple pages as you explained...I promise.
Last edited on
I am supposed to be using the get function that retrieves the member variable and the set function that assigns a value to the member variables.


But you are. Your 3 functions are good examples of how it should be. You should not have a get / set function for each member variable.

Remember a member function has access to all of the member variables. Your 3 functions make use of this, and that is how it should be.

Maybe you could post your assignment question, in full, and without any change or editing. This might clear up any misinterpretation / misconception.

This is another example of concepts which are not helped by authors of text books. They explain it is good to have private variables (that's right), then to have get / set functions (need to have those - but not for each variable). This promotes bad practice.
Maybe that's why I've found so little online information on the get/set functions specifically.

OK...I am going to type out the entire assignment as specified by the Prof (without his typos) :-)

You are storing information about the students of a school. The following information needs to be stored about each student.
*First Name
*Last Name
*City
*State
*Telephone Number
*Year (Freshman, Sophomore, Junior, Senior)
*Number of Credit Hours Enrolled (minimum 9 max 18)
*Number of Credit Hours Completed prior to current semester (between 0 to 87)
*Credit Hours left for graduation after current semester

The total credit hours required for graduartion is 90. You will make use of "classes" for writing this program. You need to write a student class and then create objects of that class to store and display the information. Please make sure that all the data members arre private and all the member functions are public. You will write the set member function (like setFirstName, setLastName, etc.) to set the value of the data members as provided by the user at runtime and the get member function (like getFirstName, getLastName, etc.) to retirieve these values for displaying. While accepting the input from the user, you would need to validate the data. For example the credit hours enrolled can't be less than 9 or more than 18. Once you have completed accepting the input from the user for all students (assume there are 5 students), display the information for each student.


PS. I haven't written the data validation yet. Working on that next.
Here is my latest code.

Can anyone tell me why it blows up when I input a number over 100 for the variable "Completed"?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <string>
#include<conio.h>
using namespace std;
 	
//declaration section
class Student {
      private:
              string FirstName;
              string LastName;
			  string City;
			  string State;
			  string Telephone;
			  string Year;
			  int Enrolled;			//number of credit hours currently enrolled
			  int Completed;		//number of credit hours completed prior to current semester
			  unsigned int Graduation;  		//number of credit hours needed for graduation after current semester
			
//interface
      public:
		    void getData()	//request user data input
			{
				cout << "Enter student first name: ";
				cin >> FirstName;
				cout << "Enter student last name:  ";
				cin >> LastName;
				cout << "Enter student city of residence:  ";
				cin >> City;
				cout << "Enter student state of residence:  ";
				cin >> State;
				cout << "Enter student telephone number:  ";
				cin >> Telephone;
				cout << "Enter the student credit hours currently enrolled (between 9 and 18):  ";
				cin >> Enrolled;
					while (Enrolled < 9 || Enrolled > 18)
					{
						cout << "The number of credit hours enrolled must be between 9 and 18." << endl;
						cout << "Please re-enter the number of credit hours enrolled: ";
						cin >> Enrolled;
					}
				cout << "Enter the student credit hours completed prior to current semester (between 0 and 87):  ";
				cin >> Completed;
					while (Completed < 0 || Completed > 87)
					{
						cout << "The number of credit hours completed must be between 0 and 87." << endl;
						cout << "Please re-enter the number of credit hours completed:  ";
						cin >> Completed;
					}
				cout << "Input accepted" << endl;
			}
			void calcGraduation()			//total hours needed for graduation are 90
			{
				Graduation = 90 - Completed - Enrolled;		//calculate how many remaining hours required for graduation
			}	
			void displayData()
			{
				cout << endl << "Student: " << FirstName << " " << LastName<< endl;
				cout << "Location: " << City << ", " << State << endl;
				cout << "Telephone: " << Telephone << endl;
				cout << "Currently enrolled: " << Enrolled << " credit hours" << endl;
				cout << "Hours completed: " << Completed << " credit hours" << endl;
				cout << "Credit hours required for graduation: " << Graduation << " credit hours" << endl;
			}
};


int main ()
{
	Student student[5];
	cout << "Please enter information for five students." <<endl;
	for (int i=0; i<5; i++)
	{
		student[i].getData();
		student[i].calcGraduation();
	}
	for (int i=0; i<5; i++)
		student[i].displayData();
return 0;	
}
Last edited on
OK...I am going to type out the entire assignment as specified by the Prof (without his typos) :-)


Awww Hell, sorry I made you do that. <(:+(

Teacher wrote:
You will write the set member function (like setFirstName, setLastName, etc.) to set the value of the data members as provided by the user at runtime and the get member function (like getFirstName, getLastName, etc.) to retirieve these values for displaying.


I am sure that I am not alone in saying that it is a shame that teachers perpetuate this misconception. Although they didn't say the get / set function [b]had to be public[/b].It is very easy to see how almost anyone would interpret the specification wrongly.

And the reason for not having public get / set functions is solid: If the get /set functions are public (they have to be) then you might as well make all the member variables public !!!!!!!

It is much better to do what you are doing now, although see my recommendation at the end for an even better idea. I would point that out to the teacher, diplomatically. I would be irate, if I lost marks for doing something correctly.

To flesh out a similar example, consider a customer information scenario. Have functions that set info split into logical groups - setNames (all of them), setAddress (3 address lines ,suburb, city, state, postcode), setEmail (all of them, 3 say) and so on. When you have a new customer, have a function that calls all the other functions. Sometimes it is worth it for a function to set one member variable, for example a phone number - people often might change their home number or mobile, not so good to have a function that forces you to re input all (5 or more say) of them.

Actually, when there are lots of variable to initialise, it is a good idea for a constructor to call an Initialise function, which would in turn call the other functions mentioned. This way you are making use of the functions for a new object, and they can be used to change an existing object.

Someone might argue that, if all these functions are public, then there is still no difference between that and making all the member variables public. That is true, the only real thing we have done is avoiding having lots of function calls, and perhaps made it a bit more logical.

If you were really worried about security, you could make all the functions private (or more likely protected) then have an authorisation function which involved a PIN number, which would then give access to a menu, which would call the functions. This provides some security for the actual users.

Even the menu by itself would be OK, because now you don't expose functions that can change data. This is a form of security for the application - to guard against other programmers who might use your object in an illegitimate way. I am talking about other coders, because in the real IT world, you write code that will be reused in some way by others.

So, now I am saying you should have one public ShowMenu function, which calls the other functions which should be private. The ShowMenu function should use a switch statement to make it elegant and scalable. Explain all this with comments in the code so your teacher can see why you have done it.

I am sorry that I have now specified something different again - but the upside might be you really understand well, because the ideas have evolved conceptually, from bad, to medium, to good.

Any way I hope you get a really good mark for the assignment.

Last edited on
Can anyone tell me why it blows up when I input a number over 100 for the variable "Completed"?


unsigned int Graduation;

1
2
3
void calcGraduation()	{		//total hours needed for graduation are 90		
	Graduation = 90 - Completed - Enrolled; //calculate how many remaining hours required for graduation
}


This gives a negative value which ain't going roll with an unsigned type.

Can you try a little experiment? Try setting your indenting to 4 spaces, instead of a tab - I am curious to see whether that will display your code better on this page.

HTH
What you're saying makes perfectly good sense. In fact, one of our upcoming projects deals with setting up a menu. It'll be an inheritance hierarchy that a bankk might use to represent customers' bank accounts.

Since this is a college class, we are learning step by step and each builds on the previous. Somewhat like math classes do I suppose.

I see why you're saying NOT to set up the get and set functions as public functions. It made little sense to me the first time I wrote it and found myself repeating the private variables one by one in the public declaration.

Since I honestly don't know HOW to use the get and set functions, I'm going to turn this in as is and, like you said, explain why I am not using them in the code. i.e. security

Thanks again for all of your help. I really appreciate it.

Oh yeah, almost forgot...why is my Completed variable blowing up when I enter a value > 100? Any ideas? Would be the last little thing before I move on to the next assignment...and have to come bug everyone again I'm sure.

Fascinating stuff!!!

:-)

We were posting at the same time - the answer to the completed variable problem is in my last post.

I will write a quick menu function for you - just to show how easy it is. Will post it shortly - hopefully 5 -10 mins.
CStudent.h

1
2
3
4
5
6
//make all your functions declarations private except this one

public:

void ShowMenu();  //in the header file


CStudent.cpp file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdlib.h>  // for the exit function
#include <iostream>

void CStudent::ShowMenu() {
    bool Quit = false;
   unsigned short Option;

    while (!Quit) {

    cout << "1.     Enter Student Data\n";
    cout << "2.     Display Student Data\n";
    cout << "3.     Quit\n\n";
    cout << "Please enter your selection" << endl;

    cin >> Option;

    switch (Option) {
        case 1:
               setData();  //I changed the name
                break;
        case 2:
               displayData();  
                break;
        case 3:
               exit (0); //exit the whole program
                break;
        default:
               cout << "Invalid Menu Option" << endl;
               break;    
     } //switch
    }//while

}// ShowMenu function 


main.cpp:

1
2
3
4
5
6
7
8
9
//includes etc
int main() {


Student student;
student.ShowMenu;

return 0;
}


This is the general idea of it, you could earn extra brownie points of you do this.

Finally here is some code for your next assignment, It is not complete, some of the return types aren't right so you can think about those yourself. You will have to write all the functions yourself.

The main design is a class for the account which is just like a record, and a class for the bank which does most of the work adding accts etc.

http://www.cplusplus.com/forum/beginner/76482/4/#msg412946


Jeeze you are lucky, when I did my study - we didn't have internet, I did absolutely every thing myself.
Last edited on
Thank you very, very much!!!

This class is an "online" class so I don't even have f2f contact with the professor, much less access to on-campus tutoring or classmates to work with.

If it wasn't for the Internet I wouldn't have any help at all, and honestly, this book we are using is not the easiest book in the world. ;-)

I would probably have to give up on the course if it wasn't for wonderful people like you who are willing to help a newbie get started.

Thanks again!

edited to add: I am actually not using tab or spaces in my code, well, at least not manually, it is the VS2010 that indents and does all that for me. It doesn't look as messy in my file as it does when I post the code here.
Last edited on
Hmmm...... I wonder if it is the same course as the last person?? :D

With the tabs / spaces, on my system (KDevelop on Linux) I can change the settings in the editor so it uses 4 spaces rather than tabs. It does it all automatically when I am writing code.

Some IDE's have indents set to 4 or 6 or whatever, but they are still tabs. When someone posts code here, the tabs are expanded to 8 spaces. Any way this is a really minor in the scheme of all things.

Did you manage to get your code into headers, implementation files, with the menu etc?
"I see why you're saying NOT to set up the get and set functions as public functions. It made little sense to me the first time I wrote it and found myself repeating the private variables one by one in the public declaration.

Since I honestly don't know HOW to use the get and set functions, I'm going to turn this in as is and, like you said, explain why I am not using them in the code. i.e. security"

Honestly, I wouldn't get too hung up on this right now. Thinking about what the public interface to your class should be is a design issue, and is probably something that will come later once you have a better idea of what classes are, how you use them, and how you write them.

I suspect what your tutor is trying to introduce you to right now are the basic ideas that:

- data members should be private
- if any other code wants to read or change the state of an object, it should do so via public interface methods

Get and Set methods are one way of doing this. Sometimes they're a good way, and sometimes they're a bad way, but that's something that comes with experience of designing classes.
@noo1

I forgot to mention there is a red herring in the banking code I gave you. One of the functions returns a this pointer, the concept of it's use in that context is all wrong, So you will have to write function yourself.

@MikeyBoy

Honestly, I wouldn't get too hung up on this right now. Thinking about what the public interface to your class should be is a design issue, and is probably something that will come later once you have a better idea of what classes are, how you use them, and how you write them.


Well I disagree, I think it is important to get this basic idea into someone's head right at the start.

Otherwise how long are they going carry on in ignorance without knowing a better way of doing it?

It took me a relatively long time to figure this out by myself, probably not helped by lots of poor examples on the net and in textbooks. It is not a very difficult concept (it is just how to use 1 class), I think the OP has it now.

Sure, class design is a "whole different kettle of krawldads", it can be fairly complex and involved to get it just right. It is something that could be learnt gradually because there area number of different concepts.

Sometimes one just needs that "piece of gold" advice so that every thing "Clicks". I was struggling with the idea of inheritance - I had two screwed up & competing Ideas, then someone told me about "IS A, HAS A, USES A" relationships. Suddenly, it all seemed to make sense to me.
Topic archived. No new replies allowed.
Pages: 12