Separate Files - the Details
1. Create a project with an appropriate name
2. The first file opened with be the one for the main - just make the appropriate changes and insert code
3. Add the remaining 2 files
a. Select Project, Add New Item and select .cpp extension
Insert the code for the implementation file
b. Select Project, Add New Item and select .h extension
Insert the code for the header file
3. Run the program
a. Open the file containing the main by selecting the appropriate tab at the top
b. Run the program as before
// GradeBook class
definition. This file presents GradeBook's public interface without
revealing the implementations of GradeBook's member
#include "stdafx.h"
#include
<string>
using namespace std;
class
GradeBook
{
public:
GradeBook( string
); // constructor that initializes courseName
void
setCourseName( string );
// function that sets the course name
string
getCourseName(); // function that gets the course
name
void
displayMessage();
// function that displays a welcome message
private:
string
courseName; // course name for this GradeBook
};
// GradeBook
member-function definitions. This file contains
#include
<iostream>
using namespace std;
#include
"GradeBook.h"
// include definition of class GradeBook
// constructor initializes
courseName with string supplied as argument
GradeBook::GradeBook(
string name )
{
setCourseName(
name ); // call set function to initialize
courseName
}
// end GradeBook constructor
// function to set the
course name
void
GradeBook::setCourseName( string name )
{
courseName =
name; // store the course name in the object
}
// function to get the
course name
string
GradeBook::getCourseName()
{
return
courseName; //
return object's courseName
}
// display a welcome
message to the GradeBook user
void
GradeBook::displayMessage()
{
// call getCourseName to get the courseName
cout <<
"Welcome to the grade book for\n" <<
getCourseName()
<<
"!" << endl;
}
// GradeBook class
demonstration after separating its interface from its implementation.
#include "stdafx.h"
#include
<iostream>
using namespace std;
#include
"GradeBook.h"
int
main()
{
// create two GradeBook objects
GradeBook
gradeBook1( "CS101 Introduction to C++
Programming" );
GradeBook
gradeBook2( "CS102 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;
}