C++ Class. © 2005 Pearson Addison-Wesley. All rights reserved 3-2 Abstract Data Types Figure 3.1...

Preview:

Citation preview

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:–– A function mainmain

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

// public functions and variables}object-list (optional);

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 outsidethe class, and they can access themember (radius)

Introduction to Classes and Objects13

C++ Gradebook Example

4 #include <iostream>

5 using std::cout;

6 using std::endl;

9 class GradeBook

10 {

11 public:

13 void displayMessage()

14 {

15 cout << "Welcome to the Grade Book!" << endl;

16 } // end function displayMessage

17 }; // end class GradeBook

20 int main()

21 {

22 GradeBook myGradeBook; // create a GradeBook object named myGradeBook

23 myGradeBook.displayMessage(); // call object's displayMessage function

24 return 0; // indicate successful termination

25 } // end main

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

};

Defined 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 constructorDate::Date () : d_(0), m_(0), y_(0) {}// copy constructorDate::Date (const Date &d) : d_(d.d_), m_(d.m_), y_(d.y_) {}// another constructorDate::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 classprivate: 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.

Recommended