Defining a class with a member function
class is a predefined variable which is used to create a class in object oriented language.
// Define class GradeBook with a member function displayMessage,
// create a GradeBook object, and call its displayMessage function.
#include <iostream>
using namespace std;
// GradeBook class definition | ||
class GradeBook | ||
{ | ||
public: | ||
// function that displays a welcome message to the GradeBook user | ||
void displayMessage() | ||
{ | ||
cout << "Welcome to the Grade Book!" << endl; | ||
} // end function displayMessage | ||
}; // end class GradeBook // function main begins program execution int main() {
Output: Welcome to the Grade Book! Example 2: // GradeBook class definition in a separate file from main. 3 #include <iostream> 4 #include <string> // class GradeBook uses C++ standard string class 5 using namespace std; 67 // GradeBook class definition 8 class GradeBook 9 { 10 public: 11 // constructor initializes courseName with string supplied as argument 12 GradeBook( string name ) 13 { 14 setCourseName( name ); // call set function to initialize courseName 15 } // end GradeBook constructor 16 17 // function to set the course name 18 void setCourseName( string name ) 19 { 20 courseName = name; // store the course name in the object 21 } // end function setCourseName 22 23 // function to get the course name 24 string getCourseName() 25 { 26 return courseName; // return object's courseName 27 } // end function getCourseName 28 29 // display a welcome message to the GradeBook user 30 void displayMessage() 31 { 32 // call getCourseName to get the courseName 33 cout << "Welcome to the grade book for\n" << getCourseName() 34 << "!" << endl; 35 } // end function displayMessage 36 private: 37 string courseName; // course name for this GradeBook 38 }; // end class GradeBook Including class GradeBook from file GradeBook.h for use in main. 3 #include <iostream> 4 #include "GradeBook.h" // include definition of class GradeBook using namespace std; // function main begins program execution 8 int main() 9 { 10 // create two GradeBook objects 11 GradeBook gradeBook1( "CS101 Introduction to C++ Programming" ); 12 GradeBook gradeBook2( "CS102 Data Structures in C++" ); 13 14 // display initial value of courseName for each GradeBook 15 cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() 16 << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() 17 << endl; 18 } // end main |
0 Comments