SlideShare a Scribd company logo
1 of 32
An Introduction To Software
Development Using C++
Class #8:
Separate Files &
Set Functions
Gradebook.cpp File
• // File: 08 Class 01 - GradeBook.cpp
• // GradeBook member-function definitions. This file
contains
• // implementations of the member functions prototyped
in GradeBook.h.
• #include <iostream>
• #include "05 Class 06 - GradeBook.h" // include
definition of class GradeBook
• using namespace std;
• // 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
• } // end function setCourseName
• // function to get the course name
• string GradeBook::getCourseName()
• {
• return courseName; // return object's courseName
• } // end function getCourseName
• // display a welcome message to the GradeBook user
• void GradeBook::displayMessage()
• {
• // call getCourseName to get the courseName
• cout << "Welcome to the grade book forn" <<
getCourseName()
• << "!" << endl;
• } // end function displayMessage
GradeBook.cpp: Defining Member
Functions in a Separate Source-Code File
• Source-code file GradeBook.cpp defines class GradeBook’s member functions,
which were declared in Gradebook.h.
• The definitions are nearly identical to the member-function definitions in the
previous program. Each member-function name in the function headers is
preceded by the class name and ::, which is known as the binary scope resolution
operator.
• This “ties” each member function to the (now separate) GradeBook class
definition, which declares the class’s member functions and data members.
• Without “GradeBook::” preceding each function name, these functions would not
be recognized by the compiler as member functions of class GradeBook—the
compiler would consider them “free” or “loose” functions, like main.
• These are also called global functions.
Image Credit: www.pervade-software.com
GradeBook.cpp: Defining Member
Functions in a Separate Source-Code File
• Such functions cannot access GradeBook’s private data or call the class’s member
functions, without specifying an object. So, the compiler would not be able to
compile these functions.
• For example, the code in setCourseName and getCourseName that access variable
courseName would cause compilation errors because courseName is not declared
as a local variable in each function—the compiler would not know that
courseName is already declared as a data member of class GradeBook.
• To indicate that the member functions in GradeBook.cpp are part of class
GradeBook, we must first include the GradeBook.h header. This allows us to
access the class name GradeBook in the GradeBook.cpp file.
Image Credit: www.digitalsday.com
GradeBook.cpp: Defining Member
Functions in a Separate Source-Code File
• When compiling GradeBook.cpp, the compiler uses the information in
GradeBook.h to ensure that :
1. The first line of each member function matches its prototype in the GradeBook.h
file—for example, the compiler ensures that getCourseName accepts no
parameters and returns a string, and that
2. Each member function knows about the class’s data members and other member
functions—for example, code that accesses courseName can access variable
courseName because it’s declared in GradeBook.h as a data member of class
GradeBook, and the code can call functions setCourseName and getCourseName,
respectively, because each is declared as a member function of the class in
GradeBook.h (and because these calls conform with the corresponding
prototypes).
Image Credit: www.chinatraderonline.com
Software Engineering Tips!
• When defining a class’s member functions outside that
class, omitting the class name and binary scope
resolution operator (::) preceding the function names
causes errors.
Image Credit: www.crosstest.com , searchengineland.com , www.gograph.com
Main.cpp File
// File Name: 08 Class 01 - main.cpp
// GradeBook class demonstration after separating
// its interface from its implementation.
#include <iostream>
#include "05 Class 06 - GradeBook.h" // include definition of class GradeBook
using namespace std;
// function main begins program execution
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;
} // end main
The Compilation and Linking Process
• The diagram shown shows the compilation and
linking process that results in an executable
GradeBook application that can be used by
instructors.
• Often a class’s interface and implementation
will be created and compiled by one
programmer and used by a separate
programmer who implements the client code
that uses the class. So, the diagram shows
what’s required by both the class-
implementation programmer and the client-
code programmer.
• The dashed lines in the diagram show the
pieces required by the class-implementation
programmer, the client-code programmer and
the GradeBook application user, respectively.
The Compilation and Linking Process
• A class-implementation programmer responsible for creating a reusable
GradeBook class creates the header GradeBook.h and the source-code file
GradeBook.cpp that #includes the header, then compiles the source-code file to
create GradeBook’s object code.
• To hide the class’s member-function implementation details, the class-
implementation programmer would provide the client-code programmer with the
header GradeBook.h (which specifies the class’s interface and data members) and
the GradeBook object code (i.e., the machine-language instructions that represent
GradeBook’s member functions).
• The client-code programmer is not given GradeBook.cpp, so the client remains
unaware of how GradeBook’s member functions are implemented.
Image Credit: allbloggingtips.co
The Compilation and Linking Process
• The client code needs to know only GradeBook’s interface to use the class and
must be able to link its object code. Since the interface of the class is part of the
class definition in the GradeBook.h header, the client-code programmer must have
access to this file and must #include it in the client’s source-code file.
manage their students’ grades. Compilers and IDEs typically invoke the linker for
you after compiling your code.
• When the client code is compiled, the compiler uses the class definition in
GradeBook.h to ensure that the main function creates and manipulates objects of
class GradeBook correctly.
• To create the executable GradeBook application, the last step is to link
1. The object code for the main function (i.e., the client code),
2. The object code for class GradeBook’s member-function implementations and
3. The C++ Standard Library object code for the C++ classes (e.g., string) used by the class-
implementation programmer and the client-code programmer.
• The linker’s output is the executable GradeBook application that instructors can
use to manage their students’ grades. Image Credit: twww.entrepreneurweb.com
Validating Data with set Functions
• In the last program, we introduced set functions for allowing clients of a class to
modify the value of a private data member. Class GradeBook defines member
function setCourseName to simply assign a value received in its parameter name
to data member courseName.
• This member function does not ensure that the course name adheres to any
particular format or follows any other rules regarding what a “valid” course name
looks like.
• Suppose that a university can print student transcripts
containing course names of only 25 characters or less.
• If the university uses a system containing GradeBook objects to generate the
transcripts, we might want class GradeBook to ensure that its data member
courseName never contains more than 25 characters.
• Our next program enhances class GradeBook’s member function setCourseName
to perform this validation (also known as validity checking).
Image Credit: blog.klocwork.com
08 Class 02 - GradeBook.h
// File Name: 08 Class 02 - GradeBook.h
// GradeBook class definition presents the public interface of
// the class. Member-function definitions appear in GradeBook.cpp.
#include <string> // program uses C++ standard string class
using namespace std;
// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // constructor that initializes a GradeBook object
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
}; // end class GradeBook
GradeBook Class Definition
• Notice that GradeBook’s class definition—and hence, its
interface—is identical to that of our previous program.
• Since the interface remains unchanged, clients of this class
need not be changed when the definition of member function
setCourseName is modified.
• This enables clients to take advantage of the improved
GradeBook class simply by linking the client code to the
updated GradeBook’s object code.
Image Credit: www.clipartpanda.com
Gradebook.cpp
// File Name: 08 Class 02 - GradeBook.cpp
// Implementations of the GradeBook member-function definitions.
// The setCourseName function performs validation.
#include <iostream>
#include "05 Class 07 - GradeBook.h" // include definition of class
GradeBook
using namespace std;
// constructor initializes courseName with string supplied as
argument
GradeBook::GradeBook( string name )
{
setCourseName( name ); // validate and store courseName
} // end GradeBook constructor
// function that sets the course name;
// ensures that the course name has at most 25 characters
void GradeBook::setCourseName( string name )
{
if ( name.length() <= 25 ) // if name has 25 or fewer
characters
courseName = name; // store the course name in the object
if ( name.length() > 25 ) // if name has more than 25 characters
{
// set courseName to first 25 characters of parameter name
courseName = name.substr( 0, 25 ); // start at 0, length of 25
cout << "Name "" << name << "" exceeds maximum length
(25).n"
<< "Limiting courseName to first 25 characters.n" << endl;
} // end if
} // end function setCourseName
// function to get the course name
string GradeBook::getCourseName()
{
return courseName; // return object's courseName
} // end function getCourseName
// display a welcome message to the GradeBook user
void GradeBook::displayMessage()
{
// call getCourseName to get the courseName
cout << "Welcome to the grade book forn" << getCourseName()
<< "!" << endl;
} // end function displayMessage
Validating the Course Name with GradeBook
Member Function setCourseName
• The enhancement to class GradeBook is in the definition of setCourseName.
• The if statement determines whether parameter name contains a valid course
name (i.e., a string of 25 or fewer characters).
• If the course name is valid, it gets stored in data member courseName. Note the
expression name.length(). This is a member-function call just like
myGradeBook.displayMessage(). The C++ Standard Library’s string class defines a
member function length that returns the number of characters in a string object.
• Parameter name is a string object, so the call name.length() returns the number of
characters in name. If this value is less than or equal to 25, name is valid and line
19 executes.
Image Credit: dik.ir
Validating the Course Name with GradeBook
Member Function setCourseName
• The if statement handles the case in which setCourseName receives an
invalid course name (i.e., a name that is more than 25 characters long).
• Even if parameter name is too long, we still want to leave the GradeBook object in
a consistent state—that is, a state in which the object’s data member courseName
contains a valid value (i.e., a string of 25 characters or less). Thus, we truncate the
specified course name and assign the first 25 characters of name to the
courseName data member (unfortunately, this could truncate the course name
awkwardly).
• Standard class string provides member function substr (short for “substring”) that
returns a new string object created by copying part of an existing string object.
Next we (i.e., name.substr( 0, 25 )) pass two integers (0 and 25) to name’s member
function substr. These arguments indicate the portion of the string name that
substr should return. The first argument specifies the starting position in the
original string from which characters are copied—the first character in every
string is considered to be at position 0. The second argument specifies the number
of characters to copy. Therefore, the call in line 24 returns a 25-character substring
of name starting at position 0 (i.e., the first 25 characters in name).
Image Credit: soashare.blogspot.com
Validating the Course Name with GradeBook
Member Function setCourseName
• For example, if name holds the value "CS101 Introduction to Programming in C++",
substr returns "CS101 Introduction to Pro".
• After the call to substr, we assign the substring returned by substr to
data member courseName.
• In this way, setCourseName ensures that courseName is always assigned a string
containing 25 or fewer characters.
• If the member function has to truncate the course name to make it valid, we then
display a warning message.
• The if statement contains two body statements—one to set the courseName to
the first 25 characters of parameter name and one to print an accompanying
message to the user.
• Both statements should execute when name is too long, so we place them in a pair
of braces, { }. Image Credit: www.catslimited.co.uk
08 Class 02 - Main.cpp
// File: 08 Class 02 - Main.cpp
// Create and manipulate a GradeBook object; illustrate
validation.
#include <iostream>
#include "05 Class 07 - GradeBook.h" // include definition of
class GradeBook
using namespace std;
// function main begins program execution
int main()
{
// create two GradeBook objects;
// initial course name of gradeBook1 is too long
GradeBook gradeBook1( "CS101 Introduction to Programming
in C++" );
GradeBook gradeBook2( "CS102 C++ Data Structures" );
// display each GradeBook's courseName
cout << "gradeBook1's initial course name is: "
<< gradeBook1.getCourseName()
<< "ngradeBook2's initial course name is: "
<< gradeBook2.getCourseName() << endl;
// modify myGradeBook's courseName (with a valid-length
string)
gradeBook1.setCourseName( "CS101 C++ Programming" );
// display each GradeBook's courseName
cout << "ngradeBook1's course name is: "
<< gradeBook1.getCourseName()
<< "ngradeBook2's course name is: "
<< gradeBook2.getCourseName() << endl;
} // end main
Testing Class GradeBook
• This program demonstrates the modified version of class GradeBook featuring
validation. Initially we create a GradeBook object named gradeBook1. Recall that
the GradeBook constructor calls setCourseName to initialize data member
courseName. In previous versions of the class, the benefit of calling
setCourseName in the constructor was not evident.
• Now, however, the constructor takes advantage of the validation provided by
setCourseName. The constructor simply calls setCourseName, rather than
duplicating its validation code. When we pass an initial course name of "CS101
Introduction to Programming in C++" to the GradeBook constructor, the
constructor passes this value to setCourseName, where the actual initialization
occurs.
• Because this course name contains more than 25 characters, the body of the
second if statement executes, causing courseName to be initialized to the
truncated 25-character course name "CS101 Introduction to Pro“. The output
contains the warning message output bymember function setCourseName.
Image Credit: checkpointech.com
Testing Class GradeBook
• We then create another GradeBook object called gradeBook2—the valid course
name passed to the constructor is exactly 25 characters.
• Next we display the truncated course name for gradeBook1 and the course name
for gradeBook2.
• We then call gradeBook1’s setCourseName member function directly, to change
the course name in the GradeBook object to a shorter name that does not need to
be truncated.
• Finally, we output the course names for the GradeBook objects again.
Image Credit: www.wolfsoftware.com
Program Output
Additional Notes on Set Functions
• A public set function such as setCourseName should carefully scrutinize any
attempt to modify the value of a data member (e.g., courseName) to ensure that
the new value is appropriate for that data item.
• For example, an attempt to set the day of the month to 37 should be rejected, an
attempt to set a person’s weight to zero or a negative value should be rejected, an
attempt to set a grade on an exam to 185 (when the proper range is zero to
100) should be rejected, and so on.
• A class’s set functions can return values to the class’s clients indicating that
attempts were made to assign invalid data to objects of the class. A client can test
the return value of a set function to determine whether the attempt to modify the
object was successful and to take appropriate action.
• To keep things simple at this early point in the course,
setCourseName just prints an appropriate message.
Image Credit: www.talkandroid.com
Software Engineering Tips!
Image Credit: searchengineland.com , www.gograph.com
• The benefits of data integrity are not automatic simply
because data members are made private—you must provide
appropriate validity checking and report the errors.
• Making data members private and controlling access,
especially write access, to those data members through
public member functions helps ensure data integrity.
What We Covered Today
1. We presented a diagram that shows the files
that class-implementation programmers and
client-code programmers need to compile
the code they write.
2. We demonstrated how set functions can be
used to validate an object’s data and ensure
that objects are maintained in a consistent
state.
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What’s In Your C++ Toolbox?
cout / cin #include if Math Class String getline
What We’ll Be Covering Next Time
1. How to define a class
and use it to create an
object.
2. How to implement a
class’s behaviors as
member functions.
3. How to implement a
class’s attributes as
data members.Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
An Introduction To Software
Development Using C++
Class #3:
Variables, Math
Today’s In-Class C++
Programming Assignment #1
• Create a class for students in
2272.
• Define 6 methods: setName,
getName, setHomeworkGrade,
setMidtermGrade,
getHomeworkGrade,
getMidtermGrade
• Create one student object, name
it, give it a homework score of 79
and a midterm score of 83. Read
these back and print them out.
• Use the 3-file system to create
your code that we covered in our
last class: header, class, and main.
Image Credit: greatergood.berkeley.edu
Today’s In-Class C++
Programming Assignment #2
• Using only the techniques we've discussed,
write a program that calculates the squares
and cubes of the numbers from 0 to 10 and
uses tabs to print the following table of
values:
Image Credit:: www.internetbillboards.net
Answer To Today’s Challenge
// In-Class Exercise #4 - Powers
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int num;
num = 0;
cout << "nnumbertsquaretcuben"
<< num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
num = num + 1;
cout << num << 't' << num * num << 't' << num * num * num <<
"n";
...
Image Credit: www.answerconstruction.com
What We Covered Today
1. Calculating cubes and
squares.
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1. Calculating your
average gas mileage.
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

More Related Content

What's hot

Final Project Presentation
Final Project PresentationFinal Project Presentation
Final Project Presentationzroserie
 
JavaDiff - Java source code diff tool
JavaDiff - Java source code diff toolJavaDiff - Java source code diff tool
JavaDiff - Java source code diff toolEnrico Micco
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMIbackdoor
 
Jf12 lambdas injava8-1
Jf12 lambdas injava8-1Jf12 lambdas injava8-1
Jf12 lambdas injava8-1langer4711
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot trainingMallikarjuna G D
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivityweb360
 
Ee java lab assignment 4
Ee java lab assignment 4Ee java lab assignment 4
Ee java lab assignment 4Kuntal Bhowmick
 
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise PlatformBIOVIA
 
Java programming language
Java programming languageJava programming language
Java programming languageSubhashKumar329
 

What's hot (17)

Java
JavaJava
Java
 
Core java
Core javaCore java
Core java
 
C progrmming
C progrmmingC progrmming
C progrmming
 
Final Project Presentation
Final Project PresentationFinal Project Presentation
Final Project Presentation
 
JavaDiff - Java source code diff tool
JavaDiff - Java source code diff toolJavaDiff - Java source code diff tool
JavaDiff - Java source code diff tool
 
Chapter 1 :
Chapter 1 : Chapter 1 :
Chapter 1 :
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMI
 
Java for C++ programers
Java for C++ programersJava for C++ programers
Java for C++ programers
 
Jf12 lambdas injava8-1
Jf12 lambdas injava8-1Jf12 lambdas injava8-1
Jf12 lambdas injava8-1
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
3.java database connectivity
3.java database connectivity3.java database connectivity
3.java database connectivity
 
Ee java lab assignment 4
Ee java lab assignment 4Ee java lab assignment 4
Ee java lab assignment 4
 
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
(ATS3-DEV08) Team Development with Accelrys Enterprise Platform
 
C++programing
C++programingC++programing
C++programing
 
Java programming language
Java programming languageJava programming language
Java programming language
 

Viewers also liked

Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysBlue Elephant Consulting
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionBlue Elephant Consulting
 
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part II
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part IIIntro To C++ - Class 03 - An Introduction To C++ Programming, Part II
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part IIBlue Elephant Consulting
 
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical Operators
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical OperatorsIntro To C++ - Class 13 - Char, Switch, Break, Continue, Logical Operators
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical OperatorsBlue Elephant Consulting
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++Blue Elephant Consulting
 
Intro To C++ - Class 04 - An Introduction To C++ Programming, Part III
Intro To C++ - Class 04 - An Introduction To C++ Programming, Part IIIIntro To C++ - Class 04 - An Introduction To C++ Programming, Part III
Intro To C++ - Class 04 - An Introduction To C++ Programming, Part IIIBlue Elephant Consulting
 
Intro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileIntro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileBlue Elephant Consulting
 
Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1Blue Elephant Consulting
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Blue Elephant Consulting
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Blue Elephant Consulting
 
Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Blue Elephant Consulting
 
Intro To C++ - Class #23: Inheritance, Part 2
Intro To C++ - Class #23: Inheritance, Part 2Intro To C++ - Class #23: Inheritance, Part 2
Intro To C++ - Class #23: Inheritance, Part 2Blue Elephant Consulting
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Examshishamrizvi
 

Viewers also liked (17)

Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, Recursion
 
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part II
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part IIIntro To C++ - Class 03 - An Introduction To C++ Programming, Part II
Intro To C++ - Class 03 - An Introduction To C++ Programming, Part II
 
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical Operators
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical OperatorsIntro To C++ - Class 13 - Char, Switch, Break, Continue, Logical Operators
Intro To C++ - Class 13 - Char, Switch, Break, Continue, Logical Operators
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Intro To C++ - Class #21: Files
Intro To C++ - Class #21: FilesIntro To C++ - Class #21: Files
Intro To C++ - Class #21: Files
 
Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++
 
Intro To C++ - Class 04 - An Introduction To C++ Programming, Part III
Intro To C++ - Class 04 - An Introduction To C++ Programming, Part IIIIntro To C++ - Class 04 - An Introduction To C++ Programming, Part III
Intro To C++ - Class 04 - An Introduction To C++ Programming, Part III
 
Intro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm ReviewIntro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm Review
 
Intro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … WhileIntro To C++ - Class 12 - For, do … While
Intro To C++ - Class 12 - For, do … While
 
Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1Intro To C++ - Class #22: Inheritance, Part 1
Intro To C++ - Class #22: Inheritance, Part 1
 
Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1Intro To C++ - Class 09 - Control Statements: Part 1
Intro To C++ - Class 09 - Control Statements: Part 1
 
Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2Intro To C++ - Class 10 - Control Statements: Part 2
Intro To C++ - Class 10 - Control Statements: Part 2
 
Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...
 
Intro To C++ - Class #23: Inheritance, Part 2
Intro To C++ - Class #23: Inheritance, Part 2Intro To C++ - Class #23: Inheritance, Part 2
Intro To C++ - Class #23: Inheritance, Part 2
 
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board ExamsC++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
C++ Notes by Hisham Ahmed Rizvi for Class 12th Board Exams
 

Similar to Intro To C++ - Class 08 - Separate Files & Set Functions

Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Asfand Hassan
 
PRG 421 Massive success / tutorialrank.com
PRG 421 Massive success / tutorialrank.comPRG 421 Massive success / tutorialrank.com
PRG 421 Massive success / tutorialrank.comBromleyz1
 
PRG 421 Inspiring Innovation / tutorialrank.com
PRG 421 Inspiring Innovation / tutorialrank.comPRG 421 Inspiring Innovation / tutorialrank.com
PRG 421 Inspiring Innovation / tutorialrank.comBromleyz24
 
introduction to c #
introduction to c #introduction to c #
introduction to c #Sireesh K
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
 
PRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.comPRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.comMcdonaldRyan108
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 
CommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docxCommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docxmonicafrancis71118
 
PRG 421 Creative and Effective/newtonhelp.com
PRG 421 Creative and Effective/newtonhelp.comPRG 421 Creative and Effective/newtonhelp.com
PRG 421 Creative and Effective/newtonhelp.commyblue101
 
PRG 421 Extraordinary Life/newtonhelp.com 
PRG 421 Extraordinary Life/newtonhelp.com PRG 421 Extraordinary Life/newtonhelp.com 
PRG 421 Extraordinary Life/newtonhelp.com myblue41
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingPurvik Rana
 
Csharp introduction
Csharp introductionCsharp introduction
Csharp introductionSireesh K
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 

Similar to Intro To C++ - Class 08 - Separate Files & Set Functions (20)

Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)Oop lec 4(oop design, style, characteristics)
Oop lec 4(oop design, style, characteristics)
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
PRG 421 Massive success / tutorialrank.com
PRG 421 Massive success / tutorialrank.comPRG 421 Massive success / tutorialrank.com
PRG 421 Massive success / tutorialrank.com
 
Group111
Group111Group111
Group111
 
PRG 421 Inspiring Innovation / tutorialrank.com
PRG 421 Inspiring Innovation / tutorialrank.comPRG 421 Inspiring Innovation / tutorialrank.com
PRG 421 Inspiring Innovation / tutorialrank.com
 
introduction to c #
introduction to c #introduction to c #
introduction to c #
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
PRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.comPRG 421 Education Specialist / snaptutorial.com
PRG 421 Education Specialist / snaptutorial.com
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
Prg421
Prg421Prg421
Prg421
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
CommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docxCommissionCalculationbuildclasses.netbeans_automatic_build.docx
CommissionCalculationbuildclasses.netbeans_automatic_build.docx
 
PRG 421 Creative and Effective/newtonhelp.com
PRG 421 Creative and Effective/newtonhelp.comPRG 421 Creative and Effective/newtonhelp.com
PRG 421 Creative and Effective/newtonhelp.com
 
PRG 421 Extraordinary Life/newtonhelp.com 
PRG 421 Extraordinary Life/newtonhelp.com PRG 421 Extraordinary Life/newtonhelp.com 
PRG 421 Extraordinary Life/newtonhelp.com 
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
The smartpath information systems c plus plus
The smartpath information systems  c plus plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
 
Csharp introduction
Csharp introductionCsharp introduction
Csharp introduction
 
advance-dart.pptx
advance-dart.pptxadvance-dart.pptx
advance-dart.pptx
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 

Intro To C++ - Class 08 - Separate Files & Set Functions

  • 1. An Introduction To Software Development Using C++ Class #8: Separate Files & Set Functions
  • 2. Gradebook.cpp File • // File: 08 Class 01 - GradeBook.cpp • // GradeBook member-function definitions. This file contains • // implementations of the member functions prototyped in GradeBook.h. • #include <iostream> • #include "05 Class 06 - GradeBook.h" // include definition of class GradeBook • using namespace std; • // 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 • } // end function setCourseName • // function to get the course name • string GradeBook::getCourseName() • { • return courseName; // return object's courseName • } // end function getCourseName • // display a welcome message to the GradeBook user • void GradeBook::displayMessage() • { • // call getCourseName to get the courseName • cout << "Welcome to the grade book forn" << getCourseName() • << "!" << endl; • } // end function displayMessage
  • 3. GradeBook.cpp: Defining Member Functions in a Separate Source-Code File • Source-code file GradeBook.cpp defines class GradeBook’s member functions, which were declared in Gradebook.h. • The definitions are nearly identical to the member-function definitions in the previous program. Each member-function name in the function headers is preceded by the class name and ::, which is known as the binary scope resolution operator. • This “ties” each member function to the (now separate) GradeBook class definition, which declares the class’s member functions and data members. • Without “GradeBook::” preceding each function name, these functions would not be recognized by the compiler as member functions of class GradeBook—the compiler would consider them “free” or “loose” functions, like main. • These are also called global functions. Image Credit: www.pervade-software.com
  • 4. GradeBook.cpp: Defining Member Functions in a Separate Source-Code File • Such functions cannot access GradeBook’s private data or call the class’s member functions, without specifying an object. So, the compiler would not be able to compile these functions. • For example, the code in setCourseName and getCourseName that access variable courseName would cause compilation errors because courseName is not declared as a local variable in each function—the compiler would not know that courseName is already declared as a data member of class GradeBook. • To indicate that the member functions in GradeBook.cpp are part of class GradeBook, we must first include the GradeBook.h header. This allows us to access the class name GradeBook in the GradeBook.cpp file. Image Credit: www.digitalsday.com
  • 5. GradeBook.cpp: Defining Member Functions in a Separate Source-Code File • When compiling GradeBook.cpp, the compiler uses the information in GradeBook.h to ensure that : 1. The first line of each member function matches its prototype in the GradeBook.h file—for example, the compiler ensures that getCourseName accepts no parameters and returns a string, and that 2. Each member function knows about the class’s data members and other member functions—for example, code that accesses courseName can access variable courseName because it’s declared in GradeBook.h as a data member of class GradeBook, and the code can call functions setCourseName and getCourseName, respectively, because each is declared as a member function of the class in GradeBook.h (and because these calls conform with the corresponding prototypes). Image Credit: www.chinatraderonline.com
  • 6. Software Engineering Tips! • When defining a class’s member functions outside that class, omitting the class name and binary scope resolution operator (::) preceding the function names causes errors. Image Credit: www.crosstest.com , searchengineland.com , www.gograph.com
  • 7. Main.cpp File // File Name: 08 Class 01 - main.cpp // GradeBook class demonstration after separating // its interface from its implementation. #include <iostream> #include "05 Class 06 - GradeBook.h" // include definition of class GradeBook using namespace std; // function main begins program execution 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; } // end main
  • 8. The Compilation and Linking Process • The diagram shown shows the compilation and linking process that results in an executable GradeBook application that can be used by instructors. • Often a class’s interface and implementation will be created and compiled by one programmer and used by a separate programmer who implements the client code that uses the class. So, the diagram shows what’s required by both the class- implementation programmer and the client- code programmer. • The dashed lines in the diagram show the pieces required by the class-implementation programmer, the client-code programmer and the GradeBook application user, respectively.
  • 9. The Compilation and Linking Process • A class-implementation programmer responsible for creating a reusable GradeBook class creates the header GradeBook.h and the source-code file GradeBook.cpp that #includes the header, then compiles the source-code file to create GradeBook’s object code. • To hide the class’s member-function implementation details, the class- implementation programmer would provide the client-code programmer with the header GradeBook.h (which specifies the class’s interface and data members) and the GradeBook object code (i.e., the machine-language instructions that represent GradeBook’s member functions). • The client-code programmer is not given GradeBook.cpp, so the client remains unaware of how GradeBook’s member functions are implemented. Image Credit: allbloggingtips.co
  • 10. The Compilation and Linking Process • The client code needs to know only GradeBook’s interface to use the class and must be able to link its object code. Since the interface of the class is part of the class definition in the GradeBook.h header, the client-code programmer must have access to this file and must #include it in the client’s source-code file. manage their students’ grades. Compilers and IDEs typically invoke the linker for you after compiling your code. • When the client code is compiled, the compiler uses the class definition in GradeBook.h to ensure that the main function creates and manipulates objects of class GradeBook correctly. • To create the executable GradeBook application, the last step is to link 1. The object code for the main function (i.e., the client code), 2. The object code for class GradeBook’s member-function implementations and 3. The C++ Standard Library object code for the C++ classes (e.g., string) used by the class- implementation programmer and the client-code programmer. • The linker’s output is the executable GradeBook application that instructors can use to manage their students’ grades. Image Credit: twww.entrepreneurweb.com
  • 11. Validating Data with set Functions • In the last program, we introduced set functions for allowing clients of a class to modify the value of a private data member. Class GradeBook defines member function setCourseName to simply assign a value received in its parameter name to data member courseName. • This member function does not ensure that the course name adheres to any particular format or follows any other rules regarding what a “valid” course name looks like. • Suppose that a university can print student transcripts containing course names of only 25 characters or less. • If the university uses a system containing GradeBook objects to generate the transcripts, we might want class GradeBook to ensure that its data member courseName never contains more than 25 characters. • Our next program enhances class GradeBook’s member function setCourseName to perform this validation (also known as validity checking). Image Credit: blog.klocwork.com
  • 12. 08 Class 02 - GradeBook.h // File Name: 08 Class 02 - GradeBook.h // GradeBook class definition presents the public interface of // the class. Member-function definitions appear in GradeBook.cpp. #include <string> // program uses C++ standard string class using namespace std; // GradeBook class definition class GradeBook { public: GradeBook( string ); // constructor that initializes a GradeBook object 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 }; // end class GradeBook
  • 13. GradeBook Class Definition • Notice that GradeBook’s class definition—and hence, its interface—is identical to that of our previous program. • Since the interface remains unchanged, clients of this class need not be changed when the definition of member function setCourseName is modified. • This enables clients to take advantage of the improved GradeBook class simply by linking the client code to the updated GradeBook’s object code. Image Credit: www.clipartpanda.com
  • 14. Gradebook.cpp // File Name: 08 Class 02 - GradeBook.cpp // Implementations of the GradeBook member-function definitions. // The setCourseName function performs validation. #include <iostream> #include "05 Class 07 - GradeBook.h" // include definition of class GradeBook using namespace std; // constructor initializes courseName with string supplied as argument GradeBook::GradeBook( string name ) { setCourseName( name ); // validate and store courseName } // end GradeBook constructor // function that sets the course name; // ensures that the course name has at most 25 characters void GradeBook::setCourseName( string name ) { if ( name.length() <= 25 ) // if name has 25 or fewer characters courseName = name; // store the course name in the object if ( name.length() > 25 ) // if name has more than 25 characters { // set courseName to first 25 characters of parameter name courseName = name.substr( 0, 25 ); // start at 0, length of 25 cout << "Name "" << name << "" exceeds maximum length (25).n" << "Limiting courseName to first 25 characters.n" << endl; } // end if } // end function setCourseName // function to get the course name string GradeBook::getCourseName() { return courseName; // return object's courseName } // end function getCourseName // display a welcome message to the GradeBook user void GradeBook::displayMessage() { // call getCourseName to get the courseName cout << "Welcome to the grade book forn" << getCourseName() << "!" << endl; } // end function displayMessage
  • 15. Validating the Course Name with GradeBook Member Function setCourseName • The enhancement to class GradeBook is in the definition of setCourseName. • The if statement determines whether parameter name contains a valid course name (i.e., a string of 25 or fewer characters). • If the course name is valid, it gets stored in data member courseName. Note the expression name.length(). This is a member-function call just like myGradeBook.displayMessage(). The C++ Standard Library’s string class defines a member function length that returns the number of characters in a string object. • Parameter name is a string object, so the call name.length() returns the number of characters in name. If this value is less than or equal to 25, name is valid and line 19 executes. Image Credit: dik.ir
  • 16. Validating the Course Name with GradeBook Member Function setCourseName • The if statement handles the case in which setCourseName receives an invalid course name (i.e., a name that is more than 25 characters long). • Even if parameter name is too long, we still want to leave the GradeBook object in a consistent state—that is, a state in which the object’s data member courseName contains a valid value (i.e., a string of 25 characters or less). Thus, we truncate the specified course name and assign the first 25 characters of name to the courseName data member (unfortunately, this could truncate the course name awkwardly). • Standard class string provides member function substr (short for “substring”) that returns a new string object created by copying part of an existing string object. Next we (i.e., name.substr( 0, 25 )) pass two integers (0 and 25) to name’s member function substr. These arguments indicate the portion of the string name that substr should return. The first argument specifies the starting position in the original string from which characters are copied—the first character in every string is considered to be at position 0. The second argument specifies the number of characters to copy. Therefore, the call in line 24 returns a 25-character substring of name starting at position 0 (i.e., the first 25 characters in name). Image Credit: soashare.blogspot.com
  • 17. Validating the Course Name with GradeBook Member Function setCourseName • For example, if name holds the value "CS101 Introduction to Programming in C++", substr returns "CS101 Introduction to Pro". • After the call to substr, we assign the substring returned by substr to data member courseName. • In this way, setCourseName ensures that courseName is always assigned a string containing 25 or fewer characters. • If the member function has to truncate the course name to make it valid, we then display a warning message. • The if statement contains two body statements—one to set the courseName to the first 25 characters of parameter name and one to print an accompanying message to the user. • Both statements should execute when name is too long, so we place them in a pair of braces, { }. Image Credit: www.catslimited.co.uk
  • 18. 08 Class 02 - Main.cpp // File: 08 Class 02 - Main.cpp // Create and manipulate a GradeBook object; illustrate validation. #include <iostream> #include "05 Class 07 - GradeBook.h" // include definition of class GradeBook using namespace std; // function main begins program execution int main() { // create two GradeBook objects; // initial course name of gradeBook1 is too long GradeBook gradeBook1( "CS101 Introduction to Programming in C++" ); GradeBook gradeBook2( "CS102 C++ Data Structures" ); // display each GradeBook's courseName cout << "gradeBook1's initial course name is: " << gradeBook1.getCourseName() << "ngradeBook2's initial course name is: " << gradeBook2.getCourseName() << endl; // modify myGradeBook's courseName (with a valid-length string) gradeBook1.setCourseName( "CS101 C++ Programming" ); // display each GradeBook's courseName cout << "ngradeBook1's course name is: " << gradeBook1.getCourseName() << "ngradeBook2's course name is: " << gradeBook2.getCourseName() << endl; } // end main
  • 19. Testing Class GradeBook • This program demonstrates the modified version of class GradeBook featuring validation. Initially we create a GradeBook object named gradeBook1. Recall that the GradeBook constructor calls setCourseName to initialize data member courseName. In previous versions of the class, the benefit of calling setCourseName in the constructor was not evident. • Now, however, the constructor takes advantage of the validation provided by setCourseName. The constructor simply calls setCourseName, rather than duplicating its validation code. When we pass an initial course name of "CS101 Introduction to Programming in C++" to the GradeBook constructor, the constructor passes this value to setCourseName, where the actual initialization occurs. • Because this course name contains more than 25 characters, the body of the second if statement executes, causing courseName to be initialized to the truncated 25-character course name "CS101 Introduction to Pro“. The output contains the warning message output bymember function setCourseName. Image Credit: checkpointech.com
  • 20. Testing Class GradeBook • We then create another GradeBook object called gradeBook2—the valid course name passed to the constructor is exactly 25 characters. • Next we display the truncated course name for gradeBook1 and the course name for gradeBook2. • We then call gradeBook1’s setCourseName member function directly, to change the course name in the GradeBook object to a shorter name that does not need to be truncated. • Finally, we output the course names for the GradeBook objects again. Image Credit: www.wolfsoftware.com
  • 22. Additional Notes on Set Functions • A public set function such as setCourseName should carefully scrutinize any attempt to modify the value of a data member (e.g., courseName) to ensure that the new value is appropriate for that data item. • For example, an attempt to set the day of the month to 37 should be rejected, an attempt to set a person’s weight to zero or a negative value should be rejected, an attempt to set a grade on an exam to 185 (when the proper range is zero to 100) should be rejected, and so on. • A class’s set functions can return values to the class’s clients indicating that attempts were made to assign invalid data to objects of the class. A client can test the return value of a set function to determine whether the attempt to modify the object was successful and to take appropriate action. • To keep things simple at this early point in the course, setCourseName just prints an appropriate message. Image Credit: www.talkandroid.com
  • 23. Software Engineering Tips! Image Credit: searchengineland.com , www.gograph.com • The benefits of data integrity are not automatic simply because data members are made private—you must provide appropriate validity checking and report the errors. • Making data members private and controlling access, especially write access, to those data members through public member functions helps ensure data integrity.
  • 24. What We Covered Today 1. We presented a diagram that shows the files that class-implementation programmers and client-code programmers need to compile the code they write. 2. We demonstrated how set functions can be used to validate an object’s data and ensure that objects are maintained in a consistent state. Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 25. What’s In Your C++ Toolbox? cout / cin #include if Math Class String getline
  • 26. What We’ll Be Covering Next Time 1. How to define a class and use it to create an object. 2. How to implement a class’s behaviors as member functions. 3. How to implement a class’s attributes as data members.Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
  • 27. An Introduction To Software Development Using C++ Class #3: Variables, Math
  • 28. Today’s In-Class C++ Programming Assignment #1 • Create a class for students in 2272. • Define 6 methods: setName, getName, setHomeworkGrade, setMidtermGrade, getHomeworkGrade, getMidtermGrade • Create one student object, name it, give it a homework score of 79 and a midterm score of 83. Read these back and print them out. • Use the 3-file system to create your code that we covered in our last class: header, class, and main. Image Credit: greatergood.berkeley.edu
  • 29. Today’s In-Class C++ Programming Assignment #2 • Using only the techniques we've discussed, write a program that calculates the squares and cubes of the numbers from 0 to 10 and uses tabs to print the following table of values: Image Credit:: www.internetbillboards.net
  • 30. Answer To Today’s Challenge // In-Class Exercise #4 - Powers #include <iostream> using std::cout; using std::endl; int main() { int num; num = 0; cout << "nnumbertsquaretcuben" << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; num = num + 1; cout << num << 't' << num * num << 't' << num * num * num << "n"; ... Image Credit: www.answerconstruction.com
  • 31. What We Covered Today 1. Calculating cubes and squares. Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 32. What We’ll Be Covering Next Time 1. Calculating your average gas mileage. Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

Editor's Notes

  1. New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.
  2. New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.