Program practice: Use constructor to initialize objects and constructor to initialize objects
Prerequisites
Each class can provideConstructorClass object initialization. constructor is a special member function. It must be defined with the same name as the class so that the compiler can distinguish it from other member functions of the class. A major difference between constructors and other functions is that constructors cannot return values, so they cannot be specified with the return type. the constructor is declared as public.
The UML diagram is as follows:
The program is as follows:
// Instantiating multiple objects of the GradeBook class and using the GradeBook constructor to specify the course name // when each GradeBook object is created.#include <iostream>using std::cout; using std::endl;#include <string> // program uses C++ standard string classusing std::string;// GradeBook class definitionclass GradeBook{public: // constructor initializes courseName with string supplied as argument GradeBook( string name ) { setCourseName( name ); // call set function to initialize courseName } // end GradeBook constructor // function to set the course name void setCourseName( string name ) { courseName = name; // store the course name in the object } // end function setCourseName // function to get the course name string getCourseName() { return courseName; // return object's courseName } // end function getCourseName // display a welcome message to the GradeBook user void displayMessage() { // call getCourseName to get the courseName cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl; } // end function displayMessageprivate: string courseName; // course name for this GradeBook}; // end class GradeBook // function main begins program executionint main(){ // create two GradeBook objects GradeBook gradeBook1( "Introduction to C++ Programming" ); GradeBook gradeBook2( "Data Structures in C++" ); // display initial value of courseName for each GradeBook cout << "gradeBook1 created for course: " << gradeBook1.getCourseName() << "\ngradeBook2 created for course: " << gradeBook2.getCourseName() << endl; return 0; // indicate successful termination} // end main
Test output
For more discussions and exchanges on Program Language, please stay tuned to this blog and Sina Weibo songzi_tea.