C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not.

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 7: User-Defined Functions II
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Classes and Objects Systems Programming.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Starting Out with C++: Early Objects 5th Edition
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 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.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
1 C++ Structures Starting to think about objects...
C++ Classes & Object Oriented Programming. Object Oriented Programming  Programmer thinks about and defines the attributes and behavior of objects. 
Review of C++ Programming Part II Sheng-Fang Huang.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
1.  A method describes the internal mechanisms that actually perform its tasks  A class is used to house (among other things) a method ◦ A class that.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Introduction To Classes Chapter Procedural And Object Oriented Programming Procedural programming focuses on the process/actions that occur in a.
1 Chapter 13 Introduction to Classes. 2 Topics 12.1 Procedural and Object-Oriented Programming 12.2 Introduction to Classes 12.3 Defining an Instance.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
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.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 Object-Oriented Programming Using C++ CLASS 1. 2 Review of Syllabus Catalog Description –An introduction to object oriented programming techniques using.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 7: Introduction.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
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.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Classes Definition A class is a data type whose variables are objects Object – a variable that has member functions as well the ability to hold.
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 12 Introduction to Classes.
 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.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
C# Programming Methods.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 11: Classes and Data Abstraction.
Chapter 3 Implementing Classes
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.
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Chapter 7: Introduction to Classes and Objects
Abstract Data Types Programmer-created data types that specify
Chapter 3: Using Methods, Classes, and Objects
Introduction to Classes
Chapter 7: Introduction to Classes and Objects
This technique is Called “Divide and Conquer”.
Object-Oriented Programming: Classes and Objects
C++ Classes & Object Oriented Programming
Introduction to Classes
Starting to think about objects...
Classes and Objects.
CLASSES AND OBJECTS.
Classes and Objects Systems Programming.
Presentation transcript:

C++ Class

© 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1 Isolated tasks: the implementation of task T does not affect task Q

C++ Program Structure Typical C++ Programs consist of:– main –A function main –One or more classes Each containing data members and member functions.

From C++ Functions to C++ Structs/Classes When to use a struct –Use a struct for things that are mostly about the data –Add constructors and operators to work with STL containers/algorithms When to use a class –Use a class for things where the behavior is the most important part –Prefer classes when dealing with encapsulation/polymorphism (later)

C++ Classes Encapsulation combines an ADT’s data with its operations to form an object –An object is an instance of a class –A class contains data members and member functions By default, all members in a class are private

C++ Classes Figure 3.10 An object’s data and methods are encapsulated

Classes: A First Look General syntax - 7 class class-name { // private functions and variables public: // public functions and variables }object-list (optional);

Defining a Class With a Member Function Class definition –Tells the compiler what member functions and data members belong to the class. –Keyword class followed by the class’s name. {} –Class body is enclosed in braces ( {} ) Specifies data members and member functions :Access-specifier public: –Indicates that a member function or data member is accessible to other functions and member functions of other classes.

Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; 7-9 Access specifiers

Classes in C++ Member access specifiers –public: can be accessed outside the class directly. –The public stuff is the interface. –private: Accessible only to member functions of class Private members and methods are for internal use only.

Introduction to Objects An object is an instance of a class Defined just like other variables Square sq1, sq2; Can access members using dot operator sq1.setSide(5); cout << sq1.getSide(); 7-11

Class Example This class example shows how we can encapsulate (gather) a circle information into one package (unit or class) class Circle { private: double radius; public: void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; No need for others classes to access and retrieve its value directly. The class methods are responsible for that only. They are accessible from outside the class, and they can access the member (radius)

Introduction to Classes and Objects 13 C++ Gradebook Example

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. Each object has its own copy. May be objects of any type

Access-specifier private 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”

Special Member Functions Constructor: –Public function member –called when a new object is created (instantiated). –Initialize data members. –Same name as class –No return type –Several constructors Function overloading

Special Member Functions class Circle { private: double radius; public: Circle(); Circle(int r); void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); }; Constructor with no argument Constructor with one argument

Constructor – 2 Examples Inline: class Square {... public: Square(int s) { side = s; }... }; Declaration outside the class: Square(int); //prototype //in class Square::Square(int s) { side = s; } 7-18

© 2005 Pearson Addison-Wesley. All rights reserved 3-19 Class Constructors and Destructors Constructors –Create and initialize new instances of a class –Have the same name as the class –Have no return type, not even void

© 2005 Pearson Addison-Wesley. All rights reserved 3-20 Class Constructors and Destructors A class can have several constructors –A default constructor has no arguments –Initializers can set data members to initial values –The compiler will generate a default constructor if one is omitted

Overloading Constructors A class can have more than 1 constructor Overloaded constructors in a class must have different parameter lists Square(); Square(int); 7-21

Implementing class methods 2.Member functions defined inside class –Do not need scope resolution operator, class name; class Circle { private: double radius; public: Circle() { radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Define d inside class

class Circle { private: double radius; public: Circle() { radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Circle::Circle(int r) { radius = r; } double Circle::getArea() { return radius * radius * (22.0/7); } double Circle:: getCircumference() { return 2 * radius * (22.0/7); } Defined outside class

Constructors A constructor has the same name as its class Establishes invariants for the class instances (objects) –Properties that always hold –Like, no memory leaks Passed parameters are used in the base class /member initialization list –You must initialize const and reference members there –Members are constructed in the order they were declared List should follow that order –Set up invariants before the constructor body is run –Help avoid/fix constructor failure More on this topic later class Date { public: Date (); Date (const Date &); Date (int d, int m, int y); //... private: int d_, m_, y_; }; // default constructor Date::Date () : d_(0), m_(0), y_(0) {} // copy constructor Date::Date (const Date &d) : d_(d.d_), m_(d.m_), y_(d.y_) {} // another constructor Date::Date (int d, int m, int y) : d_(d), m_(m), y_(y) {}

© 2005 Pearson Addison-Wesley. All rights reserved 3-25 Class Constructors and Destructors The implementation of a constructor (or any member function) is qualified with the scope resolution operator :: Sphere::Sphere(double initialRadius) : theRadius(initialRadius)

Destructors Public member function automatically called when an object is destroyed Destructor name is ~ className, e.g., ~Square Has no return type Takes no arguments Only 1 destructor is allowed per class (i.e., it cannot be overloaded) 7-26

Access Control Declaring access control scopes within a class private : visible only within the class protected : also visible within derived classes (more later) public : visible everywhere –Access control in a class is private by default but, it’s better style to label access control explicitly

Private Member Functions A private member function can only be called by another member function of the same class It is used for internal processing by the class, not for use outside of the class 7-28

Example Write a C program which accepts from the user via the keyboards, and the following data items: it_number – integer value, name – string, up to 20 characters, amount – integer value. Your program will store this data for 3 persons and display each record is proceeded by the record number. 29

Example Write a car struct that has the following fields: YearModel (int), Make (string), and Speed (int). The program has function assign_data ( ) accelerate ( ) which add 5 to the speed each time it is called, break () which subtract 5 from speed each time it is called, and display () to print out the car’s information.

Example Create a structTime that contains data members, hour, minute, second to store the time value, provide a function that sets hour, minute, second to zero, provide three function for converting time to ( 24 hour ) and another one for converting time to ( 12 hour ) and a function that sets the time to a certain value specified by three parameters

Example Coffee shop needs a program to computerize its inventory. The data will be Coffee name, price, and amount in stock, sell by year. The function on coffee are: prepare to enter stock, Display coffee data, change price, add stock (add new batch), sell coffee, remove old stock (check sell by year).

Example Design a struct named BankAccount with data: balance, number of deposits this month, number of withdrawals, annual interest rate, and monthly service charges. The program has functions: Deposit (amount) {add amount to balance and increment number of deposit by one}, Withdraw (amount) {subtract amount from balance and increment number of withdrawals by one}, CalcInterest() { update balance by amount = balance * (annual interest rate /12)}, and MonthlyPocess() {subtract the monthly service charge from balance, set number of deposit, number of withdrawals and monthly service charges to zero}.

Example Write a complete C program to –Define a person struct with members: ID, name, address, and telephone number. The functions are change_data( ), get_data( ), and display_data( ). –Declare record table with size N and provide the user to fill the table with data. –Allow the user to enter certain ID for the Main function to display the corresponding person's name, address, and telephone number.