Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Slide 10Slide 11Slide 12Slide 13COSC 181 – Foundations of Computer ProgrammingClass 8Initializing Classes with “Constructors”Figure 3.5PreviouslycourseName was set to empty when we instantiated the object GradeBook myGradeBook;cout << “course name is:” << myGradeBook.getCourseName() << endl;Now – Figure 3.7Instead we are going to useGradeBook myGradeBook(“COSC 181: C++”);How do we do this?Fig. 3.7 (lines 16 – 17)public:GradeBook (string name){setCourseName (name);} …Created a new special member functionHas the same name as the classCalled a constructorCalled when an object of the class is instantiatedWhat you didn’t knowALL classes with no other constructors have constructors called “default constructors”Classes can have either implicitly or explicitly defined default constructorsDefault constructors are those that take no parametersClasses with defined constructors will not be implicitly given default constructorsUpdated Class DiagramNow with Constructor<<constructor>> + GradeBook (name : String)Placing a class in a separate fileSo far in the same .cpp source file: class ClassName {//private: public: class functions and attributes }; int main() {// different variables and calls, etc. system(“PAUSE”); return 0; }The class declaration and the main function don’t have to be in the same source file (.cpp file)Using “header” filesInstead, place the class definition(s) in a separate fileclass ClassName {//private: public: class functions and attributes };Place the entire class definition in a file and save it as GradeBook.hDo not compile or attempt to run GradeBook.hHas no main() functionInstead, header files must be included in .cpp filesSee Fig 3.9 and Fig 3.10Note, figure 3.9 is saved as a header fileIt has a .h file extensionFigure 3.10 is saved as a .cpp file.It is the file that is going to be compiledIt has the main() functionLine 7 of Fig 3.10#include “GradeBook.h”This allows the instantiations that happen in lines 13 and 14Seperating Interface from FunctionalityFurther divide the code into 3 filesGradeBook.h fileGradeBook.cpp fileMainprogram.cpp fileWhy?A person working on the Mainprogram.cpp file will have to have access to GradeBook.hGradeBook.h has the implementation code for the classes methodsThis is generally not desirableMainprogram programmer only needs to know how to call the functionsFig. 3.11GradeBook.h fileGive function “declarations”Fig 3.12GradeBook.cppGives function “instantiations”Fig 3.13Fig03_13.cppMakes use of the classNote: Compilation must be handled differently with this approachHowever, we will not make immediate use of this method, though details about the method may appear on a test in limited formReview
View Full Document