11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

170Part III: Introduction to ClassesCreating a member functionTo demonstrate member functions, start by defining a class Student. Onepossible representation of such a class follows (taken from the programCallMemberFunction):class Student{public:// add a completed course to the recordfloat addCourse(int hours, float grade){// calculate the sum of all courses times// the average gradefloat weightedGPA;weightedGPA = semesterHours * gpa;// now add in the new coursesemesterHours += hours;weightedGPA += grade * hours;gpa = weightedGPA / semesterHours;}// return the new gpareturn gpa;};int semesterHours;float gpa;The function addCourse(int, float) is called a member function of theclass Student. In principle, it’s a property of the class like the data memberssemesterHours and gpa.There isn’t a special name for functions or data that are not members of aclass, but I’ll refer to them as non-members.The member functions do not have to precede the data members as in thisexample. The members of a class can be listed in any order — I just prefer toput the functions first.For historical reasons, member functions are also called methods. This termoriginated in one of the original object-oriented languages. The name madesense there, but it makes no sense in C++. Nevertheless, the term has gainedpopularity in OO circles because it’s easier to say than “member function.”(The fact that it sounds more impressive probably doesn’t hurt either.) So, ifyour friends start spouting off at a dinner party about “methods of the class,”just replace methods with member functions and reparse anything they say.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!