Chapter 5
Implementing Classes in C++
Encapsulation
• To encapsulate components is to contain
them
– Encapsulation is an example of a black box
• OOP combines the data and functions that
manipulate the data into a single package
called objects.
– Data – The object’s attributes
– Functions – The object’s behavior
• An interface intercedes between you and
the inner workings of an object
2
Encapsulation Classes
• C++ distinguishes among
– public class members
• accessible to anybody
– protected class members
• accessible to members of this or derived
classes
– private
• accessible just to members of this class
• A C++ structure (struct) is simply a class
whose members are public by default
• C++ base classes can also be public,
private, or protected 3
C vs C++ implementation
• C implements using struct and C++ uses Classes
struct coord class Coord
{ {
int x; public:
int y; int x;
}; int y;
};
struct coord location; Coord location;
location.x = 7; location.x = 7;
location.y = 8; location.y = 8;
printf(“%d”,location.y); cout << location.y;
4
Classes in C++
• A class is a category of objects; it is a new
data type
– Classes provide a description of an object
– Classes provide a convenient way to group
related data and the functions that use the
data
– When you create an object from the class,
you automatically create all the related
fields
• Abstract data type (ADT): a type that you
define
5
Data Members of a Class
• Declared in the body of the class
• May be public or private
• Exist throughout the life of the object.
• Stored in class object.
6
Designing Classes
• If you need a class for students, you should ask:
– What shall we call it?
– What are its attributes?
– What methods are needed by Student?
• In most cases, you declare both fields and
functions
– You declare a field using a data type and an
identifier
– You declare a function by writing its prototype,
which serves as the interface to the function
7
Data Abstraction in C++
• Based on C struct type
• Class is the encapsulation device
– all of the class instances (objects) of a class share a
single copy of the member functions
– each instance of a class has its own copy of the
class data members
– instances can be static, semidynamic, or explicit
dynamic
• Information Hiding
– private clause for hidden entities
– public clause for interface entities
– protected clause - for inheritance 8
Defining Classes: Example
Student class that includes one function
• To instantiate an object is to declare or create
it
Student aStudent;
aStudent.displayStudentData();
• A function that uses your class is a class
client 9
Gradebook Example
10
Member Functions with Parameters
11
Member Functions with Parameters (cont.)
31 // prompt for and input course name
32 cout << "Please enter the course name:" << endl;
33 getline( cin, nameOfCourse ); // read a course name with blanks
34 cout << endl; // output a blank line
35
36 // call myGradeBook's displayMessage function
37 // and pass nameOfCourse as an argument
38 myGradeBook.displayMessage( nameOfCourse );
39 return 0; // indicate successful termination
40 } // end main Passing an argument to the
Please enter the course name: member function
CS101 Introduction to C++ Programming
Welcome to the grade book for
CS101 Introduction to C++ Programming!
12
Considering Scope when Defining Member
Functions
The Customer Class
13
Considering Scope when Defining
Member Functions (cont’d)
The setFields() function of the Customer class, using scope
resolution with the field names
A version of setFields() in which the scope resolution operator is required
14
Static Class Members
• When a class field is static, only one memory
location is allocated
– All members of the class share a single storage
location for a static data member of that same class
• When you create a non-static variable within a
function, a new variable is created every time
you call that function
• When you create a static variable, the variable
maintains its memory address and previous
value for the life of the program
15
Defining Static Data Members
16
Defining Static Data Members
(continued)
• Static variables are sometimes called class
variables, class fields, or class-wide fields
because they don’t belong to a specific
object;
– they belong to the class
17
Static Functions
• A static function can be used without a
declared object
• Static functions can access static variables
• Static functions cannot access non-static
variables
• Non-static functions can access static
variables (provided there is an object)
18
Static Functions (cont’d)
19
Visibility rules
• Public and Private parts of an object
declaration/definition
• Reasons to put things in the
declaration:
– so programmers can get at them
– so the compiler can understand them
• At the very least the compiler needs to
know the size of an object,
– That's why private fields have to be in
declaration
20
private Access Modifier
• Makes any member accessible only to
member functions of the class.
• May be applied to data members and member
functions
• Default access for class members
• Encourages “information hiding”
21
Using Public Functions to Alter Private Data
The Student Class and a demonstration main() function
22
Using Public Functions to Alter Private Data
(cont’d)
23
Example 2
// This program demonstrates a simple class.
#include <iostream.h>
// Rectangle class declaration.
class Rectangle
{
private:
float width;
float length;
float area;
public:
void setData(float, float);
void calcArea(void);
float getWidth(void);
float getLength(void);
float getArea(void);
}; 24
Program continues
// The double full colon is used when the methods are implemented
// outside the class.
// setData copies the argument w to private member width and
// l to private member length.
void Rectangle::setData(float w, float l)
{
width = w;
length = l;
}
// calcArea multiplies the private members width and length.
// The result is stored in the private member area.
void Rectangle::calcArea(void)
{
area = width * length;
25
}
Program continues
// getWidth returns the value in the private member width.
float Rectangle::getWidth(void)
{
return width;
}
// getLength returns the value in the private member length.
float Rectangle::getLength(void)
{
return length;
}
// getArea returns the value in the private member area.
float Rectangle::getArea(void)
{
return area;
} 26
Program continues
void main(void)
{
Rectangle box;
float wide, long;
cout << "This program will calculate the area of a\n";
cout << "rectangle. What is the width? ";
cin >> wide;
cout << "What is the length? ";
cin >> long;
box.setData(wide, long);
box.calcArea();
cout << "Here is the rectangle's data:\n";
cout << "width: " << box.getWidth() << endl;
cout << "length: " << box.getLength() << endl;
cout << "area: " << box.getArea() << endl;
}
27
Program Output
This program will calculate the area of a
rectangle. What is the width? 10 [Enter]
What is the length? 5 [Enter]
Here is the rectangle's data:
width: 10
length: 5
area: 50
28
Public and Private Members
1 // Fig. 19.5: fig19_05.cpp
2 // Define class GradeBook that contains a courseName data member
3 // and member functions to set and get its value;
4 // Create and manipulate a GradeBook object with these functions.
5 #include <iostream>
6 using std::cout;
7 using std::cin;
8 using std::endl;
9
10 #include <string> // program uses C++ standard string class
11 using std::string;
12 using std::getline;
13
14 // GradeBook class definition
15 class GradeBook set function modifies private
16 {
data
17 public:
18 // function that sets the course name
19 void setCourseName( string name )
20 {
21 courseName = name; // store the course name in the object
22 } // end function setCourseName
23 get function accesses private
24 // function that gets the course name
data
25 string getCourseName()
26 {
27 return courseName; // return the object's courseName
28 } // end function getCourseName
29
29
Public and Private Members
(continued)
30 // function that displays a welcome message
31 void displayMessage()
32 {
33 // this statement calls getCourseName to get the
34 // name of the course this GradeBook represents
35 cout << "Welcome to the grade book for\n" << getCourseName() << "!"
36 << endl;
37 } // end function displayMessage
38 private:
39 string courseName; // course name for this GradeBook Use set and get functions,
40 }; // end class GradeBook even within the class
41
42 // function main begins program execution private members accessible
43 int main() only to member functions of the
44 { class
default constructor
45 string nameOfCourse; // string of characters to store the course name
46 GradeBook myGradeBook; // create a GradeBook object named myGradeBook
47
Accessing private data
48 // display initial value of courseName
49 cout << "Initial course name is: " << myGradeBook.getCourseName()
outside class definition
50 << endl;
51
30
Public and Private Members
(continued)
52 // prompt for, input and set course name
53 cout << "\nPlease enter the course name:" << endl;
54 getline( cin, nameOfCourse ); // read a course name with blanks
55 myGradeBook.setCourseName( nameOfCourse ); // set the course name
56
57 cout << endl; // outputs a blank line
58 myGradeBook.displayMessage(); // display message with new course name
59 return 0; // indicate successful termination
60 } // end main
Modifying private data outside class
Initial course name is:
definition
Please enter the course name:
CS101 Introduction to C++ Programming
default setting from constructor
is an empty string!!
Welcome to the grade book for
CS101 Introduction to C++ Programming!
31
Constructors
• Constructor:– a function used to initialize the data of an
object of a class
– Same name as class itself
– Cannot return anything, not even void
– A class may define more than one constructor
• With different parameter lists Compiler provides one
• Default constructor has no parameters if you do not!
• Called automatically
– When class object is declared as automatic variable
– By new operator
• Specialized constructors
– Default (no parameters)
– Copy (bitwise copy of an object – provided if not defined) 32
– Conversion (converts one data type to another)
Constructors
• Used for automatically building objects
• Are always member functions
– May be overloaded
– May have default arguments
– Do not have a return type (not even void)
– Always have the same name as the containing class
• Are called automatically invoked when an object is
instantiated
• Can be as complex as needed but are often simple and
used to initialize member data
33
Example
// This program demonstrates a constructor.
#include <iostream.h>
class Demo
{
public:
Demo(void); // Constructor
};
Demo::Demo(void)
{
cout << "Welcome to the constructor!\n";
}
void main(void)
{
Demo demoObj; // Declare a Demo object;
cout << "This program demonstrates an object\n";
cout << "with a constructor.\n";
34
}
Program Output
Welcome to the constructor.
This program demonstrates an object
with a constructor.
35
Constructor Arguments
• When a constructor does not have to
accept arguments, it is called an object’s
default constructor.
• Like regular functions, constructors may
accept arguments, have default
arguments, be declared inline, and be
overloaded.
36
Constructor Example
1 // Fig. 19.7: fig19_07.cpp
2 // Instantiating multiple objects of the GradeBook class and using
3 // the GradeBook constructor to specify the course name
4 // when each GradeBook object is created.
5 #include <iostream>
6 using std::cout;
7 using std::endl;
8
9 #include <string> // program uses C++ standard string class
10 using std::string;
11
Constructor has same name
12 // GradeBook class definition
13 class GradeBook
as class and no return type
14 {
15 public:
16 // constructor initializes courseName with string supplied as argument
17 GradeBook( string name )
18 {
19 setCourseName( name ); // call set function to initialize courseName
20 } // end GradeBook constructor
21
22 // function to set the course name
Initialize data member
23 void setCourseName( string name )
24 {
25 courseName = name; // store the course name in the object
26 } // end function setCourseName
37
27
Constructor Example
28 // function to get the course name
29 string getCourseName()
30 {
31 return courseName; // return object's courseName
32 } // end function getCourseName
33
34 // display a welcome message to the GradeBook user
35 void displayMessage()
36 {
37 // call getCourseName to get the courseName
38 cout << "Welcome to the grade book for\n" << getCourseName()
39 << "!" << endl;
40 } // end function displayMessage
41 private:
42 string courseName; // course name for this GradeBook
43 }; // end class GradeBook
44
38
Constructor Example
45 // function main begins program execution
46 int main()
47 {
48 // create two GradeBook objects
49 GradeBook gradeBook1( "CS101 Introduction to C++ Programming" );
50 GradeBook gradeBook2( "CS102 Data Structures in C++" );
51
52 // display initial value of courseName for each GradeBook
53 cout << "gradeBook1 created for course: " << gradeBook1.getCourseName()
54 << "\ngradeBook2 created for course: " << gradeBook2.getCourseName()
55 << endl;
56 return 0; // indicate successful termination Creating objects implicitly calls
the constructor
57 } // end main
gradeBook1 created for course: CS101 Introduction to C++ Programming
gradeBook2 created for course: CS102 Data Structures in C++
39
Destructors
• Destructor:– a function used to clean up an
object of a class prior to deleting that object
– Class name preceeded by '~'
– No parameters, no result Compiler provides one
if you do not!
• Called automatically
– object goes out of scope
– when object is deleted
– By delete operator
• Used for:
– Deallocate dynamic memory
– Close files and remove temporary files
40
– Close network connections and databases
Example
// This program demonstrates a destructor.
#include <iostream.h>
class Demo
{
public:
Demo(void); // Constructor
~Demo(void); // Destructor
};
Demo::Demo(void)
{
cout << "Welcome to the constructor!\n";
}
41
Program continues
Demo::~Demo(void)
{
cout << "The destructor is now running.\n";
}
void main(void)
{
Demo demoObj; // Declare a Demo object;
cout << "This program demonstrates an object\n";
cout << "with a constructor and destructor.\n";
}
42
Program Output
Welcome to the constructor!
This program demonstrates an object
with a constructor and destructor.
The destructor is now running.
43
Class in a Separate Header File for
Reusability
• .cpp files for source-code implementations
– Class implementations
– Main programs
– Test programs
– …
• Header files
– Separate files in which class definitions are placed.
– Allow compiler to recognize the classes when used
elsewhere.
– Generally have .h filename extensions
• Driver file
– A program used to test software (such as classes).
– Contains a main function so it can be executed.
44
Interfaces versus
Implementation
• Interface
– Describes what services a class’s clients can use
and how to request those services.
• without revealing how the class carries out the services.
• a class definition listing only public member function
prototypes.
– A class’s interface consists of the class’s public
member functions (services).
• Defined in class header file (.h)
45
Interfaces versus
Implementation
• Implementation of member functions
– In a separate source-code file for a class
• Use binary scope resolution operator (::) to tie
each member function to the class definition.
– Implementation details are hidden.
• Client code does not need to know the
implementation.
46
Interfaces versus Implementation (Example)
1 // Fig. 19.11: GradeBook.h
2 // GradeBook class definition. This file presents GradeBook's public
3 // interface without revealing the implementations of GradeBook's member
4 // functions, which are defined in GradeBook.cpp.
5 #include <string> // class GradeBook uses C++ standard string class
6 using std::string;
7
8 // GradeBook class definition Interface contains data members and
9 class GradeBook member function prototypes
10 {
11 public:
12 GradeBook( string ); // constructor that initializes courseName
13 void setCourseName( string ); // function that sets the course name
14 string getCourseName(); // function that gets the course name
15 void displayMessage(); // function that displays a welcome message
16 private:
17 string courseName; // course name for this GradeBook
18 }; // end class GradeBook
47
Interfaces versus Implementation
(continued)
1 // Fig. 19.12: GradeBook.cpp
2 // GradeBook member-function definitions. This file contains
3 // implementations of the member functions prototyped in GradeBook.h.
4 #include <iostream>
GradeBook implementation is placed
5 using std::cout;
in a separate source-code file
6 using std::endl;
7
8 #include "GradeBook.h" // include definition of class GradeBook Include the header file to access
9 the class name GradeBook
10 // constructor initializes courseName with string supplied as argument
11 GradeBook::GradeBook( string name )
12 {
13 setCourseName( name ); // call set function to initialize courseName
14 } // end GradeBook constructor
15 Binary scope resolution operator
16 // function to set the course name ties a function to its class
17 void GradeBook::setCourseName( string name )
18 {
19 courseName = name; // store the course name in the object
20 } // end function setCourseName
21
48
Interfaces versus Implementation (continued)
22 // function to get the course name
23 string GradeBook::getCourseName()
24 {
25 return courseName; // return object's courseName
26 } // end function getCourseName
27
28 // display a welcome message to the GradeBook user
29 void GradeBook::displayMessage()
30 {
31 // call getCourseName to get the courseName
32 cout << "Welcome to the grade book for\n" << getCourseName()
33 << "!" << endl;
34 } // end function displayMessage
49
Client of the Interface
1 // Fig. 19.13: fig19_13.cpp
2 // GradeBook class demonstration after separating
3 // its interface from its implementation.
4 #include <iostream>
5 using std::cout;
6 using std::endl;
7
8 #include "GradeBook.h" // include definition of class GradeBook
9
10 // function main begins program execution
11 int main()
12 {
13 // create two GradeBook objects
14 GradeBook gradeBook1( "CS101 Introduction to C++ Programming" );
15 GradeBook gradeBook2( "CS102 Data Structures in C++" );
16
17 // display initial value of courseName for each GradeBook
18 cout << "gradeBook1 created for course: " << gradeBook1.getCourseName()
19 << "\ngradeBook2 created for course: " << gradeBook2.getCourseName()
20 << endl;
21 return 0; // indicate successful termination
22 } // end main
gradeBook1 created for course: CS101 Introduction to C++ Programming
gradeBook2 created for course: CS102 Data Structures in C++
50