Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure.

Slides:



Advertisements
Similar presentations
Chapter 12 Separate Compilation and Namespaces. Abstract Data Type (ADT) ADT: A data type consisting of data and their behavior. The abstraction is that.
Advertisements

1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Starting Out with C++: Early Objects 5th Edition
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 11: Classes and Data Abstraction
Lecture 9 Concepts of Programming Languages
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Learners Support Publications Classes and Objects.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
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
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
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.
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.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
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?
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
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, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
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:
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
Procedural and Object-Oriented Programming
Classes C++ representation of an object
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?
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
Review: Two Programming Paradigms
Introduction to Classes
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?
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Introduction to Classes
Classes and Data Abstraction
Chapter 9 Objects and Classes
Classes and Objects.
Classes C++ representation of an object
CS 144 Advanced C++ Programming February 21 Class Meeting
More C++ Classes Systems Programming.
Presentation transcript:

Chapter 10 Defining Classes

User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure composed of data members that are different types. – class: an extension of struct. It contains both data members (attributes) and member functions (methods).

Structures Is a data type composed of data members that are different types. Defining syntax: struct structName { type data1; type data2; … type dataN; }; Declaration syntax: structName varName;

Structure defintition struct STime { int hour; int minute; int second; }; STime lunchTime, classTime; struct SDate { int year; int month; int day; } myBirthDay, laborDay; Separate variable declarationsCombine with variable declarations (Directly declare)

Notes for structure defintition Structure definitions do not allocate space. Space is allocated when a structure variable is defined. Since different compilers allocate filler space between fields differently, use the sizeof() operator to determine structure size for space allocation. – sizeof(n) - operator returns the number of bytes needed to store an object. It is machine dependent. DO NOT FORGET THE SEMICOLON AFTER THE DECLARATION!!! Two different structures can have data members with the same name struct Fertilizerstruct Crop{ double quantity; double nitrogen;double size;};

The Dot. operator Used to access data members. Has highest precedence. Ex: struct STime { int hour; int minute; int second; }; void main () { STime classTime; cout << "Enter the class time as hours, minutes and seconds, separate by spaces: “; cin >> classTime.hour >> classTime.minute >> classTime.second; classTime.hour--; // Set it to one hour early cout << "The updated class time is " << classTime.hour << " hours, "; cout << classTime.minute << "minute(s) and " << classTime.second << " second(s)\n"; }

Initializing Structures Can initialize a structure variable when it is declared. SDate taxDate = {2013, 4, 15}; // year = 2013, month = 4, day = 15 Initializing values must be given in order that corresponses to the order of data members in the structure definition. SDate taxDate = {4, 15, 2013}; // year = 4, month = 15, day = 2013 SDate taxDate = {2013}; // year = 2013, month = 0, day = 0 SDate taxDate = {2013, 15}; // year = 2013, month = 15, day = 0 SDate taxDate = {2013, 4, 15, 3}; // syntax error

Hierarchical Structures Structures cannot contain an instance of itself (defined recursively) However, structures can contain other structures (nested structures). struct SDate { int year; int month; int day; }; struct SStudentInfo { char name; SDate bDay; double gpa; };

Advantages of Hierarchical Structures Separated structure can be used in one program for different purposes. Ex: read in a day into SDate thisday and then search record for persons with this birthday and send card. Structure is a collection of related information. So, it is considered one entity when hierarchically used inside other structures. Ex: It is clear that month, day and year are one entity (SDate). Details of month, day and year are pushed to lower level. We are not concerned with their structure until we actually need to use them.

Access hierarchical structure members Used applicable dot operations. Ex: struct SDate { int year, month, day; }; struct SStudentInfo { char name; SDate bDay; double gpa; }; void main () { SStudentInfo JohnDoe = {“John Doe”, {1990, 12, 31}, 3.50}; SStudentInfo anotherStudent; char first[15], last[15]; cout << "Enter the student first name and last name separated by a space: " cin >> first >> last; strcat (first, last); strcpy (anotherStudent.name, first); cout << "Enter the student birthdays (in order of year, month and day), separated by spaces : " cin >> anotherStudent.bDay.year >> anotherStudent.bDay.month >> anotherStudent.bDay.day; cout << “John Doe’s birthday is: ” << JohnDoe.bDay.month << “/” << JohnDoe.bDay.day << “/”<< JohnDoe.bDay.year << endl; }

Assignment Operator in Structure Used to assign value of one structure variable to another. Assigns each data member of the right side to its corresponding data member on the left side matched. Ex: SDate myBD = {1900, 12, 31}; SDate yourBD = myBD; // Your BD is now 12/31/1900 SStudentInfo aStudent; aStudent.bDay = myBD;

Structures and Arrays Structures contain arrays: struct SStudentInfo { char name; SDate bDay; float quiz[5]; }; SStudentInfo aStudents; cout << aStudents.name; cout << aStudents.quiz[1]; An array of structures: SStudentInfo csci123Students[25]; cout << csci123Students[2].name; cout << csci123Students[2].bDay.year; csci123Students[2].quiz[3] = 9.5;

Classes An extension of struct: It contains both data members (attributes) and member functions (methods). The first characteristic of classes is encapsulation. Encapsulation: the binding together of data and functions into a single entity (object). This allows the object to be used in different applications because its data parts are defined and the behaviors it can do (member functions) are defined. It is a known quantity— just like we know how integers behave and what they contain! Includes 2main parts: definition and implementation

Class definition consists of specifications of data members (variable, constants, types) and member function prototypes. The prototypes in the public section are all the programmer needs. Usually stored in the header file (ClassName.h) Usually has 2 sections: public and private. Might have another section: protected.

Class definition (example) class CDate { public: CDate(); // default constructor CDate(int m, int d, int y); // parameterized constructor CDate(const CDate& aDay); // copying constructor ~CDate(); // destructor int getMonth(); // accessor int getDay(); // accessor void setMonth(int m); // mutator void setDay(int d); // mutator void display(); // a member function int year; private: int month; int day; bool isValid(); };

Class public and private sections Public section: – It tells users what an object of the class can do. – Anything defined in the public section can be seen and used by other parts of the program. Private section: – Hidden from users. – Includes local data members and functions used only in the class implementation. – Private data members can only be changed by member functions. This prevents the object from being changed illegally by the application program.

Class implementation contains the member function definitions. This is the procedural abstraction of the class. It could be stored below main or in a.cpp file since it is executable C++ code. However, it is usually stored in the class implementation file (ClassName.cpp)

Class implementation (example) #include "Date.h" CDate::CDate () { month = 1; day = 1; year = 1900; } CDate::CDate (int m, int d, int y) { month = m; day = d; year = y; } CDate::CDate (const CDate& aDay) { month = aDay.month; day = aDay.day; year = aDay.year; } CDate::~CDate () {} int CDate::getMonth() { return month; } int CDate::getDay() { return day; } void CDate::setMonth(int m) { month = m; } void CDate::setDay(int d) { day = d; } void CDate::display() { cout << month <<'/' << day << '/' << year; } bool CDate::isValid () { return (month > 0 && month < 13) && (day > 0 && day 0); }

Class implementation (example) #include "Date.h" CDate::CDate () : month(1), day(1), year(1900) {} CDate::CDate (int m, int d, int y) : month(m), day(d), year(y) {} CDate::CDate (const CDate& aDay) : month(aDay.month), day(aDay.day), year(aDay.year) {} CDate::~CDate () {} int CDate::getMonth() { return month; } int CDate::getDay() { return day; } void CDate::setMonth(int m) { month = m; } void CDate::setDay(int d) { day = d; } void CDate::display() { if (isValid()) cout << month <<'/' << day << '/' << year; else cout << “Invalid date to display”; } bool CDate::isValid () { return (month > 0 && month < 13) && (day > 0 && day 0); }

Class common operators Scope resolution :: – tells the compiler that this function is a member of the class (classname::functionname). Dot operator. – tells the compiler to go to the class definition for this object and use the function defined in that class object.functionname(parameters). Assignment operator = – Like a struct, the assignment operation assigns each data member of the right side to its corresponding data member on the left side matched

Accessor and Mutator functions Assessor functions: Since the application can’t see the private data members of a class, the class must provide public functions that return the private data. Functions that are public and allow access to the member variables are called accessor functions. – Ex: getMonth(), getDay() Mutator Functions: Functions that allow the changing of private data members. – Ex: setMonth(), setDay();

Class object initialization The assumption in classes is that we wouldn’t declare an object unless we wanted to put meaningful data in it. If we do not tell the compiler what information to put in the object, the object will contain garbage. Therefore, we need to create an automatic function that will create an object containing valid data. That function is called constructor.

Constructor A function which creates and initializes an object Has the same name as the class name. Associates an initializing function with the class object (instance, variable). Does not return a type or use the word void Declared in public section.

Constructor types Constructor sets initial values 3 ways: – Default constructor: sets to base value. Only 1. – Paramertized constructor: gets values from parameter list. Can have 1 or more. – Copy constructor: copies one object into another. Only 1.

Constructor Notes Every class must have at least a default constructor The constructor function is called every time an object is declared. This insures that an object does not have garbage in it. Initializers can be used within the constructor. CDate myBD(12, 31, 1999); A constructor can be explicitly called. CDate hisBD = CDate (1, 1, 2000); Do NOT use () when declaring an object if you want to use the default constructor for initialization: CDate yourBD(); // invalid code CDate yourBD; // OK

Class Header and Implementation files Classes are stored in 2 separate files: –.h file contains the definition section- user interface (class header file) –.cpp file contains the implementation section (class implementation file)

Using #ifndef Used to ensure that a header file has not already been included resulting in duplicate copies of the class. States that the header file is not defined previously then use this definition--otherwise, do not include the class again. // Date.h #ifndef _DATE_H_ #define _DATE_H_ #include … using namespace std; class CDate { … }; #endif // Date.cpp #include “Date.h” CDate::CDate () { month = 1; day = 1; year = 1900; } CDate::CDate (int m, int d, int y) { month = m; day = d; year = y; }

Using newly defined class Treat new class as new data type. Use dot operator to access data members and member functions (class attributes and methods) #include “Date.h” using namespace std; void main () { CDate yourBD; cout << "Enter your birthday as month, day and year, separate by spaces: “; cin >> yourBD.month >> yourBD.day >> yourBD.year; // Syntax error } //Default constructor called Private data members

Using newly defined class (cont.) #include “Date.h” using namespace std; void main () { CDate yourBD; cout << "Enter your birthday as month, day and year, separate by spaces: ”; int m, d; cin >> m >> d >> yourBD.year; yourBD.setMonth(m); yourBD.setDay(d); cout << “Your birthday is: " << yourBD.display() << endl; CDate LincohnBD(2, 12, 1809); cout << “Abraham Lincoln's birthday is: " << LincohnBD.display() << endl; CDate twinBrotherBD(yourBD); cout << “Your twin brother’s birthday is: " << twinBrotherBD.display(); } Enter your birthday as month, day and year, separate by spaces: Your birthday is: 8/31/2000 Abraham Lincoln's birthday is: 2/12/1809 Your twin brother’s birthday is: 8/31/2000 //Default constructor called //Parameterized constructor called //Copying constructor called

Abstract Data Types (ADT) Data type: consists of a description of the data and the operations that can be performed on them. – Examples: complex numbers, vectors, points, matrices, shapes Data abstraction: separation of logical properties of data structure from its implementation. – abstract data types(ADT): a model of a data type consisting of its attributes and its behavior(complex numbers) – information hiding: preventing the user from access to information that is internal to the functions/ data type. (i.e. local variables or functions which are submodules of higher functions) Abstraction: High-level operations appropriate to the data type are isolated from the low-level implementation details associated with the data type. User is not concerned with how real numbers are stored or added by the computer, just that that operation exists-that is hidden from the user (data abstraction). – Ex: A circle class would have an object (circle) and methods to draw, expand, contract, erase, etc. We don’t need to know how the circle is drawn or erased, just that we can do it and how to call the function.