Download presentation
Presentation is loading. Please wait.
Published byClarence White Modified over 8 years ago
1
C++ Class
2
© 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
3
C++ Program Structure Typical C++ Programs consist of:– main –A function main –One or more classes Each containing data members and member functions.
4
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)
5
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
6
C++ Classes Figure 3.10 An object’s data and methods are encapsulated
7
Classes: A First Look General syntax - 7 class class-name { // private functions and variables public: // public functions and variables }object-list (optional);
8
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.
9
Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; 7-9 Access specifiers
10
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.
11
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
12
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)
13
Introduction to Classes and Objects 13 C++ Gradebook Example
14
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
15
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”
16
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
17
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
18
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
19
© 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
20
© 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
21
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
22
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
23
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
24
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) {}
25
© 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)
26
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
27
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
28
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
29
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
30
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.
31
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
32
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).
33
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}.
34
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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.