C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CS-212 Intro to C++. Abstract Data Type Abstraction of a real world object as a mathematical entity Implementation independent model of the entity Emphasis.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
1 Lab Session-XIV CSIT121 Spring 2002 b Namespaces b First Class Travel b Lab Exercise 14 (Demo) b Lab Exercise b Practice Problem.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
CS 106 Introduction to Computer Science I 03 / 23 / 2007 Instructor: Michael Eckmann.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
Review of C++ Programming Part II Sheng-Fang Huang.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Introduction to Object Oriented Design. Topics Designing Your Own Classes Attributes and Behaviors Class Diagrams.
Constructors and Other Tools Version 1.0 Topics Constructors & Destructors Composition const Parameter Modifier const objects const functions In-line.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
Introduction to Object Oriented Design Version 1.1.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Chapter 10 Classes and Objects In-Depth. Chapter 10 A class provides the foundation for creating specific objects, each of which shares the general attributes,
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Chapter 9 Classes: A Deeper Look, Part I Part II.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Object Oriented Programming Session # 03.  Abstraction: Process of forming of general and relevant information from a complex scenarios.  Encapsulation:
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Java Programming, Second Edition Chapter Three Using Methods, Classes, and Objects.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Topics Instance variables, set and get methods Encapsulation
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Introduction to Classes and Objects CS-2303, C-Term C++ Program Structure Typical C++ Programs consist of:– main –A function main –One or more classes.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Object-Oriented Programming Using C++ Third Edition Chapter 7 Using Classes.
Classes and Objects.
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Lecture 9 Concepts of Programming Languages
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Defining Classes and Methods
Chapter 4: Writing classes
Object Oriented Programming
Dr. Bhargavi Dept of CS CHRIST
Classes and Objects.
Defining Classes and Methods
Object Oriented Programming in java
Defining Classes and Methods
Defining Classes and Methods
Lecture 9 Concepts of Programming Languages
Presentation transcript:

C++ Classes in Depth

Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects

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

Let’s review some concepts from CS 1400

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

Let’s consider an object that represents a time.

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

We hide the data from anyone outside of the object by making it “private” A Time object Joe WageEarner $

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

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

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 $ getHour ( ) setHour( )

Then we write statements that send messages to the objects An “Time” object named joe Joe WageEarner $ getHour ( ) setHour ( ) joe.getHours( );

An Object’s Attributes and Behaviors Should Work Together this is called cohesion

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

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.

A class is said to be an abstraction of the real world object that we are modeling. Classes are sometimes called Abstract Data Types.

We use a UML Class Diagram to document the data and methods contained in our class.

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.

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

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

It is important that class diagrams be drawn precisely and that they conform to the form shown in these examples.

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); };

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.

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

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; }

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

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 ::

“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

“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.

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.

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 = ;

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.

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; }

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.

Creating Objects

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

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.

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.

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.

Sending Messages to Objects

startTime.setHour(8); message object name. method name parameter startTime hour minute

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.

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

Designing a Class

Classes model real world things, like … * an employee * a student * a car * a rectangle * a circle * a bowling team...

* 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

Draw a Class Diagram Rectangle - width: int - height: int

* 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

Draw a Class Diagram Rectangle - width: int - height: int - color: string + Rectangle(:int, :int, :string) + setHeight(:int) + setWidth(:int) + getArea( ): int

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

Idea of a Rectangle List attributes operations Class Diagram.h File Design Summary

The following code creates a Rectangle object using a non-parameterized constructor. Rectangle joe; Don’t do this! Rectangle joe( );

When an object is created like this Employee joe; the employee object is stored on the stack. It is a local variable.

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&);

Lab #3 will give you some practice designing a class and writing a program in C++ to use it.