1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
Road Map Introduction to object oriented programming. Classes
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Using C++ Functions Object-Oriented Programming Using C++ Second Edition 4.
Chapter 11: Classes and Data Abstraction
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
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.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Learners Support Publications Classes and Objects.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
CPS120: Introduction to Computer Science Lecture 14 Functions.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
1 Using C++ Functions Object-Oriented Programming Using C++ Second Edition 4.
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.
1 Using Templates COSC 1567 C++ Programming Lecture 10.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
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.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Structures  Structure types  Pointers and structure types  Structures.
Object-Oriented Programming Using C++ Third Edition Chapter 7 Using Classes.
Structures and Classes
Programming Logic and Design Seventh Edition
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Object-Oriented Programming Using C++
Learning Objectives Structures Structure types
Object-Oriented Programming Using C++ Second Edition
Object-Oriented Programming Using C++ Second Edition
Classes and Objects.
Object-Oriented Programming Using C++
Submitted By : Veenu Saini Lecturer (IT)
More C++ Classes Systems Programming.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4

2 Objectives Structures Define a class Declaration and implementation Public and private access modifiers Private functions Scope resolution operator with class fields and functions Static variables Pointer this

Structures 2 nd aggregate data type: struct Recall: aggregate meaning "grouping" –Recall array: collection of values of same type –Structure: collection of values of different types Treated as a single item, like arrays Major difference: Must first "define" struct –Prior to declaring any variables 3

Structure Types Define struct globally (typically) No memory is allocated –Just a "placeholder" for what our struct will "look like" Definition: struct CDAccountV1  Name of new struct "type" { double balance;  member names double interestRate; int term; }; 4

Declare Structure Variable With structure type defined, now declare variables of this new type: CDAccountV1 account; –Just like declaring simple types –Variable account now of type CDAccountV1 –It contains "member values" Each of the struct "parts" 5

Accessing Structure Members Dot Operator to access members –account.balance –account.interestRate –account.term Called "member variables" –The "parts" of the structure variable –Different structs can have same name member variables No conflicts 6-6

Structure Example: Display 6.1 A Structure Definition (1 of 3) 7

Structure Example: Display 6.1 A Structure Definition (2 of 3) 8

Structure Example: Display 6.1 A Structure Definition (3 of 3) 9 Ex4-0-1.cpp Ex4-0-2.cpp

Structure Pitfall Semicolon after structure definition –; MUST exist: struct WeatherData { double temperature; double windVelocity; };  REQUIRED semicolon! –Required since you "can" declare structure variables in this location 6-10

Structure Assignments Given structure named CropYield Declare two structure variables: CropYield apples, oranges; –Both are variables of "struct type CropYield" –Simple assignments are legal: apples = oranges; Simply copies each member variable from apples into member variables from oranges 6-11

Structures as Function Arguments Passed like any simple data type –Pass-by-value –Pass-by-reference –Or combination Can also be returned by function –Return-type is structure type –Return statement in function definition sends structure variable back to caller 6-12

Initializing Structures Can initialize at declaration –Example: struct Date { int month; int day; int year; }; Date dueDate = {12, 31, 2003}; –Declaration provides initial data to all three member variables 6-13

14 Creating Classes with Declaration and Implementation Sections Classes provide a convenient way to group related data The Student class is an abstract data type (ADT) Student is a type you define, as opposed to types like char and int that are defined by C++ One advantage of creating the Student class is that when you create a Student object, you automatically create all the related Student fields

15 Creating Classes with Declaration and Implementation Sections Another advantage is the ability to pass a Student object into a function, or receive a Student object from a function as a returned value, and automatically pass or receive all the individual fields that each Student contains The first step to creating a class involves determining the attributes of an object, and subsequently dealing with the object as a whole

16 Encapsulating Class Components Just as the internal components of a radio are hidden, when you write a program and create a class name for a group of associated variables, you hide, or encapsulate, the individual components Sometimes you want to change the state of some components, but often you want to think about the entry as a whole and not concern yourself with the details

17 Designing Classes You can think of the built-in scalar types of C++ as classes You do not have to define those classes; the creators of C++ have already done so For most object-oriented classes, then, you declare both fields and functions You declare a function by writing its prototype, which serves as the interface to the function

18 Designing Classes When you declare a class with a function definition, you then create an object of that class, the object possesses more than access to each field—it also possesses access to the function

19 Implementing Member Functions After you create a member function’s prototype, you still must write the actual function When you construct a class, you create two parts –The first part is a declaration section, which contains the class name, variables (attributes), and function prototype –The second part create is an implementation section, which contains the functions themselves

Dot and Scope Resolution Operator Used to specify "of what thing" they are members Dot operator: –Specifies member of particular object Scope resolution operator: –Specifies what class the function definition comes from 6-20

21 Student Class That Includes One Function Definition and Implementation

22 Implementing Class Functions Ex4-0-3.cpp

23 Data Hiding and Encapsulation Object-oriented programmers strive to make their classes similar to real-world objects, which usually do not provide access to their inner workings; access is available only to the interface One technique programmers use to provide more complete object encapsulation is to make object’s data private One major asset of object-oriented programming is that the information hiding can be accomplished more completely than it is with the procedures used in procedural programs

24 Data Hiding and Encapsulation Traditional procedural languages do not allow data to be declared as private; object-oriented languages do In C++, data hiding means that you can make data members of a class inaccessible to functions that are not part of that class Within a C++ class, you accomplish data encapsulation by making the data private instead of public

25 Data Hiding and Encapsulation When you compile the program, you receive error messages indicating that the fields idNum, lastName, and gradePointAverage are inaccessible

26 Using Public Functions to Alter Private Data You gain a major advantage when you make a data field private Once you create a class, including writing and debugging all of its member functions, outside functions can never modify or erroneously use the private member data of any object in the class When you create and test a class, and store its definition in a file, programs that use the definition can be prevented from using member data incorrectly

27 Using Public Functions to Alter Private Data If a private member of your Student class, such as idNum, must be a four-digit number, or if you require that the idNumber always be preceded by a pound sign, functions that are not a member of your class can never change those rules (either intentionally or by accident)

28 Using Public Functions to Alter Private Data To setLastName() function shown in Figure 5-9 is a member of the Student class You can determine this because the class header contains the Student class name and the scope resolution operator

29 Using Public Functions to Alter Private Data When you use the setIdNum() function with an object like aJunior, you are assured that aJunior receives a valid idNum Figure 5-11 shows how the setGradePointAverage() function can be written to accept a double argument and assure that the argument is no more than 4.0 before assigning it to any Student’s gradePointAverage field

30 Using a Complete Class Figure 5-12 shows the entire Student class, all its member functions, and a short program that uses the class EX4-1.cpp

31 Using Private Functions Not all function are public When you think of real-world objects, such as kitchen appliances, there are many public functions you control through an interface: adjusting the temperature, etc.

32 Using Private Functions EX4-2.cpp

33 Considering Scope When Defining Member Functions There are circumstances when the scope resolution operator is required with a class field name Whenever there is a conflict between local and class variable names, you must use the scope resolution operator to achieve the results you want The member variable with the same name is hidden unless you use the scope resolution operator

34 Considering Scope When Defining Member Functions In the second function, idNum refers to only the function’s local variable named idNum

35 Using Static Class Members A C++ object is an instantiation of a class that can contain both data members and methods When you create an object, a block of memory is set aside for the data members Sometimes every instantiation of a class requires the same value

36 Using Static Class Members To avoid a waste, you declare the athletic fee variable as static, meaning that it is shared by all the instances A class variable that you declare to be static is the same for all objects that are instantiations of the class Static variables are sometimes called class variables because they do not belong to a specific object; they belong to the class

37 Defining Static Data Members Because it uses only one memory location, a static data member is defined (given a value) in a single statement outside the class definition Most often this statement appears just before the class implementation section

38 A Class That Contains a Static AthleticFee Field Ex4-3.cpp Even though each Student declared in the program has a unique ID number, all Student objects share the athletic fee, which was assigned a value just once A static class member exists, even when you have not instantiated any objects of the class

39 Using Static Functions In the program, the athleticFee field is public, which is why you can access it directly, as in Student::athleticFee = ; If it were private, you would have to use a public function to access the value, as with any other private variable You cannot use a static function to access a non-static field because static functions do not receive a pointer to the object that uses the function You will use a public static function to display the private static variable Ex4-4.cpp

40 Understanding the this Pointer When you define a class, you include fields and functions If the class has one non-static field and one static field such as the Employee class shown in Figure 5-23, and you then declare two Employee objects, you reserve storage for two versions of the non- static field However, you store only one version of the static field that every object can use C++ does not store member functions separately for each instance of a class

41 Understanding the this Pointer One copy of each member function is stored, and each instance of a class uses the same function code

42 Understanding the this Pointer Ex4-5.cpp

43 Understanding the this Pointer Because only one copy of each function exists, when you call a function, it needs to know which objects to use To ensure that the function uses the correct object, you use the object’s name, such as clerk or driver, with the dot operator Within the displayValue() function, the address of the object is stored in a special pointer called the this pointer

44 Understanding the this Pointer The this pointer holds the memory address of the current object that is using the function That is why it is named this—it refers to “this object” as opposed to any other object The this pointer also is passed to member functions when they receive additional, explicitly stated arguments

45 Using the this Pointer Explicitly Within any member function, you can prove that the this pointer exists and that it holds the address of the current object You do so by using the this pointer to access the object’s data fields Ex4-6.cpp

46 Using the Pointer-to-Member Operator The functions operate by using the C++ pointer-to-member operator, which looks like an arrow and is constructed by a programmer by using a dash followed by a right angle bracket (or greater-than sign) Any pointer variable that is declared to point to a class object can be used to access individual fields or functions of that class by using the parentheses and the asterisk

47 Using the Pointer-to-Member Operator Ex4-7.cpp

Structures versus Classes Structures –Typically all members public –No member functions Classes –Typically all data members private –Interface member functions public Technically, same –Perceptionally, very different mechanisms 6-48 Ex4-8.cpp

49 Summary Each class you define is an abstract data type, or a group type with its own fields and functions A technique programmers use to provide more complete object encapsulation is to make most objects’ data private You can make functions private when you want to hide their use from client programs You can use the scope resolution operator with class fields and functions

50 Summary When you declare a class variable to be static, only one copy of the variable is stored, no matter how many class objects you instantiate When you create a class, one copy of each member function is stored Polymorphism is the object-oriented program feature that allows the same operation to be carried out differently, depending on the object