Download presentation
Presentation is loading. Please wait.
1
C++ Classes in Depth
2
Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects
3
Objectives At the completion of this topic, students should be able to: Design classes for use in a C++ program Explain the difference between a class and an object Explain what attributes and behaviors are Explain the terms encapsulation and data hiding Create a program that uses a programmer designed class
4
Let’s review some concepts from CS 1400
5
Objects are used to model real-world things. You can think of an object as a rather complex variable that contains multiple chunks of data
6
Let’s consider an object that represents a time.
7
Real world objects have attributes An object’s attributes describe its “state of being” What things do we normally associate with the state of a time? seconds minutes hours am/pm
8
We hide the data from anyone outside of the object by making it “private” A Time object Joe WageEarner 12356 $12.50 40
9
The attributes of an object are stored inside the object as data members. An “Time” object The hour value is stored as an integer The minute value is stored as an integer am or pm is stored as a string 3 35 pm
10
An object also has behaviors behaviors define how you interact with the object What can you do with a time? Get the hours set the hours
11
Behaviors are expressed as methods that give us controlled access to the data. These are “public” so that we can see them. An “Time” object Joe WageEarner 12356 $12.50 40 getHour ( ) setHour( )
12
Then we write statements that send messages to the objects An “Time” object named joe Joe WageEarner 12356 $12.50 40 getHour ( ) setHour ( ) joe.getHours( );
13
An Object’s Attributes and Behaviors Should Work Together this is called cohesion
14
Encapsulation Time object getHour( ) hour minute calling method we should not allow code outside of the object to reach in and change the data directly. Instead, we call methods in the object to do it for us. member data is declared as private member methods are declared as public The terms public and private are called access modifiers
15
A Class is a blueprint that a program uses when it creates an object. A class reserves no space in memory When an object is created from the class blueprint, memory is reserved to hold the object’s attributes. An object is known as an instance of the class. Each object has it’s own space and data.
16
A class is said to be an abstraction of the real world object that we are modeling. Classes are sometimes called Abstract Data Types.
17
We use a UML Class Diagram to document the data and methods contained in our class.
18
Time A UML class diagram is used to describe a class in a very precise way. A class diagram is a rectangle. At the top of the rectangle is the class name. A line separates the class name from the rest of the diagram.
19
Time - hour: int Following the class name we write the data members of the class. A line separates the data members from the rest of the diagram. access modifier: + public - private data member name data type
20
Time - hour: int - minute: int Following the data members, we write the member functions. + getHour( ): int access modifier + public - private method name parameters return type
21
It is important that class diagrams be drawn precisely and that they conform to the form shown in these examples.
22
In C++ the class definition usually goes into a separate file called the header file. It has a file extension of.h mytime.h class Time { private: int hour; int minutes; string amOrPm public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ); void setHour( int n); void setMinutes( int n); void setAmOrPm(string a); };
23
In C++ the class definition usually goes into a separate file called the header file. It has a file extension of.h mytime.h class Time { private: int hour; int minutes; string amOrPm public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ); void setHour( int n); void setMinutes( int n); void setAmOrPm(string a); }; Notice that getter functions (functions that do not change the state of the object) are declared as const functions.
24
Declaring Member Data class Time { private: int hour; int minutes; string amOrPm; } Member data is always “private” Indent each line inside the block data type variable name
25
Declaring Member Data We call data members of a class “Instance Data” because each instance (object) of the class will contain its own unique copy of this data. class Time { private: int hour; int minutes; string amOrPm; }
26
Declaring Member Methods public class Time { private:... public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ) const; void setHour( int n); void setMinutes( int n); void setAmOrPm(string a); Member methods are usually public return type function name parameters When would you make a method private? These are called function prototypes
27
In C++ the code that implements the member functions of the class goes into a related file with the file extension.cpp mytime.cpp #include “mytime.h”... string Time::getHour( ) const { return hour; } void Time::setHour( double n) { hour = n }... always #include the.h file for this class Class name followed by ::
28
“Setter”Methods void Time::setHour(int hr) { hour = hr; } setters never return anything they are usually named “set” plus the name of the instance variable they will store the value in. setters always take a parameter
29
“Getter”Methods int Time::getHour( ) const { return hour; } getters always return something they are usually named “get” plus the name of the instance variable they will return the value of. getters take no parameters The const keyword is required to tell the compiler that the function does not alter the object.
30
The methods of a class are the public services or the public interface that this class offers to its clients. Clients are neither aware of nor involved in the implementation details of these methods. Clients care what a method does, but not how it does it.
31
Static Data Every instance object has its own copy of all of the instance variables in a class. What if you want to have all objects of a class share a single instance of a variable? For example, all savingsAccount objects might have the same interest rate. To do this, declare the variable as private static double interestRate = 0.0725;
32
Static Methods A static method can be called without creating an object of the class that it belongs to. Static methods don’t operate on data in an object unless the data itself is declared as static. When you invoke a static method you use the name of the class instead of an object name.
33
The this reference Every instance object contains a variable named this that is a pointer to itself. The keyword is often used when you want to explicitly name a variable as a data member of this object. For example, in the Time class we have discussed is a method void setHour( int hr) { hour = hr; }
34
The this reference Using the this reference we could write: void setHour( int hr) { this->hour = hr; } More to come on pointers and “this” in a few weeks.
35
Creating Objects
36
class Time { private: int hour; int minute;... } Class definition Time startTime; this statement takes the Time class definition and uses it to create the object “startTime”. When creating the object, storage is allocated for the each of the data members defined in the class. startTime hour minute
37
Constructors When an object is created, the data members inside the object need to be initialized. Otherwise, they take on the Residual values of the bits in the memory that the object occupies. You can use a constructor to initialize data members in a class to values passed in to the constructor as parameters.
38
Constructors Time::Time( ) { hour = 0; minutes = 0; } No return type is mentioned A constructor has the same name as the class. You only need to write a non-parameterized constructor if you need one, If you do not write a non-parameterized constructor, the compiler creates one for you. It takes no parameters and its body is empty, so it does not initialize anything.
39
Constructors Time::Time(int hr, int min ) { hour = hr; minutes = min; } You can also write a parameterized constructor. If you write a parameterized constructor, you must also write a non-parameterized one. The non-parameterized constructor is called the default constructor.
40
Sending Messages to Objects
41
startTime.setHour(8); message object name. method name parameter startTime hour minute
42
startTime.setHour(8); message parameter startTime hour minute void setHour(int hr) { hour = hr; } This statement send the setHour message to the object named startTime. As the method executes, the value of the parameter hr is stored in the instance variable hour.
43
The code that creates objects and sends messages to them is typically written in main( ) in what we call a driver. This code is saved in a separate.cpp file. driver.cpp #include #include “time.h” using namespace std; int main( ) { Time newTime;... myTime.setHour(3);... } always #include the.h file for any class used in main
44
Designing a Class
45
Classes model real world things, like … * an employee * a student * a car * a rectangle * a circle * a bowling team...
46
* A Rectangle What words would you use to describe a rectangle, i.e. what are its attributes? These become data members of the class. it’s width it’s height it’s color
47
Draw a Class Diagram Rectangle - width: int - height: int
48
* A Rectangle What can I do with/to a Rectangle? These become member functions of the class. create one change it’s height or width calculate it’s area
49
Draw a Class Diagram Rectangle - width: int - height: int - color: string + Rectangle(:int, :int, :string) + setHeight(:int) + setWidth(:int) + getArea( ): int
50
Create the.h File class Rectangle { private: int height; int width; string color; public: Rectangle ( ); Rectangle (int, int, string); void setWidth( int ); void setHeight( int ); int getArea( ) const; }; For brevity I have not included the function prologues
51
Idea of a Rectangle List attributes operations Class Diagram.h File Design Summary
52
The following code creates a Rectangle object using a non-parameterized constructor. Rectangle joe; Don’t do this! Rectangle joe( );
53
When an object is created like this Employee joe; the employee object is stored on the stack. It is a local variable.
54
Passing Objects as Parameters We always want to pass objects by reference. To keep from having side effects, pass by constant reference. For example: void printRectangle(const Rectangle&);
55
Lab #3 will give you some practice designing a class and writing a program in C++ to use it.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.