COSC 181 Foundations of Computer Programming Class 8 Initializing Classes with Constructors Figure 3 5 Previously courseName was set to empty when we instantiated the object GradeBook myGradeBook cout course name is myGradeBook getCourseName endl Now Figure 3 7 Instead we are going to use GradeBook 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 function Has the same name as the class Called a constructor Called when an object of the class is instantiated What you didn t know ALL classes with no other constructors have constructors called default constructors Classes can have either implicitly or explicitly defined default constructors Default constructors are those that take no parameters Classes with defined constructors will not be implicitly given default constructors Updated Class Diagram Now with Constructor constructor GradeBook name String Placing a class in a separate file So 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 files Instead place the class definition s in a separate file class ClassName private public class functions and attributes Place the entire class definition in a file and save it as GradeBook h Do not compile or attempt to run GradeBook h Has no main function Instead header files must be included in cpp files See Fig 3 9 and Fig 3 10 Note figure 3 9 is saved as a header file Figure 3 10 is saved as a cpp file It has a h file extension It is the file that is going to be compiled It has the main function Line 7 of Fig 3 10 include GradeBook h This allows the instantiations that happen in lines 13 and 14 Seperating Interface from Functionality Further divide the code into 3 files GradeBook h file GradeBook cpp file Mainprogram cpp file Why A person working on the Mainprogram cpp file will have to have access to GradeBook h GradeBook h has the implementation code for the classes methods This is generally not desirable Mainprogram programmer only needs to know how to call the functions Fig 3 11 GradeBook h file Give function declarations Fig 3 12 GradeBook cpp Gives function instantiations Fig 3 13 Fig03 13 cpp Makes use of the class Note Compilation must be handled differently with this approach However we will not make immediate use of this method though details about the method may appear on a test in limited form Review Time
View Full Document