Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 Introduction to Classes and Objects

Similar presentations


Presentation on theme: "Chapter 3 Introduction to Classes and Objects"— Presentation transcript:

1 Chapter 3 Introduction to Classes and Objects
C++, How to Program Deitel & Deitel Spring 2010 CS1600 Yanjun Li

2 Basic Object Technology Concept
Objects: people, animals, plants, cars. We study objects’ attributes and observe objects’ behaviors. Dogs Attributes : name, color, breed, hungry, age Behaviors: barking, fetching, wagging tail Students Attributes : name, age, SSN, Female/Male, class, major. Behaviors: taking courses, doing homework, taking exams and so on. We design computer programs to describe/represent real-world objects or virtual objects. Spring 2010 CS1600 Yanjun Li

3 Traditional Programming
Procedure based. A computer program has been viewed as a logical procedure that takes input data, processes it, and produces output data. The programming challenge was seen as how to finish the job (solve the problem) in a certain steps. Spring 2010 CS1600 Yanjun Li

4 Object-Oriented Programming
Object-Oriented Programming may be seen as a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Spring 2010 CS1600 Yanjun Li

5 Object-Oriented Programming
Advantages: Reusable OOP: well designed module could be used on future projects. Procedural Programming: repeatedly reinvent the wheel. Maintenance OOP: modular, easy to maintain, interchanged as units without disassembly of the modules. Procedural Programming: not well modularized, change the structure, start from scratch. Spring 2010 CS1600 Yanjun Li

6 Class A class is a user-defined type.
A class defines the abstract characteristics of a group similar objects Attributes (fields or properties) Behaviors (methods or functions). A class is a user-defined type. Can be used to create objects: Variables of the class type C++ is an extensible language Spring 2010 CS1600 Yanjun Li

7 Question ? To design a class, we should define attributes and behaviors. Student class Computer class Customer class Spring 2010 CS1600 Yanjun Li

8 Example Let’s design a class for ShoppingCart:
The class ShoppingCart would consist of features shared by all shopping cart, such as size, owner and quantities of products (characteristics), and the ability to check whether it is full, calculate total price, add a product, delete a product (behavior). Spring 2010 CS1600 Yanjun Li

9 A C++ Class In C++: A C++ class has two parts:
Data members: variables which are used to represent the attributes of a class. Member functions: functions which are used to define the behaviors of a class. A C++ class has two parts: Interface of a Class Implementation of a Class Spring 2010 CS1600 Yanjun Li

10 The Interface The interface of a Class like a manual
Describes what the objects of this class can do for us, and also how to request these services from objects. Allow compiler to recognize the classes when used elsewhere. The interface includes Data Members Member Function Prototypes The interface of classA is in a header file : classA.h Spring 2010 CS1600 Yanjun Li

11 Example: GradeBook Class
Data Member: int courseNumber; Member function: void displayMessage(); Header file: GradeBook.h class GradeBook { public: void displayMessage(); private: int courseNumber; }; Spring 2010 CS1600 Yanjun Li

12 Access Specifier Labels
public: The function or data member is available to the public private: The function or data member can be used only in member functions of the same class. Functions outside the class (main function) or member functions of other classes could not access them. The default access for class members. As a rule of thumb, data members should be declared private and member functions should be declared public. Spring 2010 CS1600 Yanjun Li

13 The Implementation The implementation of a class defines the member functions of the class. The implementation of classA is in a source file : classA.cpp The source file includes: #include statement to include the interface of the class The implementation of member functions Use binary scope resolution operator (::) to tie each member function to the class definition. Spring 2010 CS1600 Yanjun Li

14 #include preprocessor directive
Used to include header files Instructs C++ preprocessor to replace directive with a copy of the contents of the specified file Quotes indicate user-defined header files Preprocessor first looks in current directory If the file is not found, looks in C++ Standard Library directory Angle brackets indicate C++ Standard Library Preprocessor looks only in C++ Standard Library directory Spring 2010 CS1600 Yanjun Li

15 Example: GradeBook Class
Source file : GradeBook.cpp #include <iostream> using std::cout; using std::endl; #include “GradeBook.h” void GradeBook::displayMessage( ) { cout << “Welcom to Grade Book for Course No.” << courseNumber << endl; } Spring 2010 CS1600 Yanjun Li

16 Compiling Command Compile the source-code file (GradeBook.cpp) to create GradeBook’s object code. Command: g++ -c GradeBook.cpp Object code : GradeBook.o To hide the implementation details of GradeBook’s member functions, only the header file GradeBook.h and the object code for GradeBook (GradeBook.o) are provided to these programmers who will use GradeBook in their codes. Spring 2010 CS1600 Yanjun Li

17 Use GradeBook Class Create a GradeBook object GradeBook myGradeBook;
className objectName; Memory courseNumber Space for data member of object myGradeBook Spring 2010 CS1600 Yanjun Li

18 Use GradeBook Class Dot operator (.)
Used to access an object’s data members and member functions. Call this member function ( request one service from this GradeBook object ) myGradeBook.displayMessage( ); objectName.memberFunction(para.); Spring 2010 CS1600 Yanjun Li

19 Driver File Driver files Example: test.cpp (driver file)
Program used to test software (such as classes) Contains a main function so it can be executed. Example: test.cpp (driver file) #include “GradeBook.h” //include the definition // of GradeBook class int main() { GradeBook myGradeBook; myGradeBook.displayMessage(); return 0; } Spring 2010 CS1600 Yanjun Li

20 Compilation and Linking Process
Compiles test.cpp, links GradeBook.o and makes executable test.out Command: g++ test.cpp GradeBook.o –o test.out Compiling class object code, compiling main function object code, linking them to produce the executable file with one command: g++ test.cpp GradeBook.cpp –o test.out Spring 2010 CS1600 Yanjun Li

21 Implementation File as the Driver File
main function could be put in the implementation file (classA.cpp) to test classA. #include “GradeBook.h” void GradeBook::displayMessage() { }//end of member function int main() }//end of main function Compiling command: g++ GradeBook.cpp –o test.out Spring 2010 CS1600 Yanjun Li

22 set Functions and get Functions
public member functions that allow clients of a class to set or get the values of private data members. set functions sometimes called mutators (setter) and get functions sometimes called accessors (getter). Allows the creator of the class to control how clients access private data members. Should also be used by other member functions of the same class. Spring 2010 CS1600 Yanjun Li

23 Set Functions Set functions update the data members directly. Example:
//in GradeBook.h void setCourseNumber(int n); //in GradeBook.cpp void GradeBook::setCourseNumber(int n) { courseNumber = n; } Spring 2010 CS1600 Yanjun Li

24 Get Functions Get the value of a data member. Example:
//in GradeBook.h int getCourseNumber( ); //in GradeBook.cpp int GradeBook::getCourseNumber( ) { return couresNumber; } Spring 2010 CS1600 Yanjun Li

25 Constructor A special member function: to initialize an object of the class when the object is created. must have the same name as the class. Never return any value (not even void). Declared as public. Usually the data members of the class are initialized inside the constructor. The constructor is called when an object of this class is created. Spring 2010 CS1600 Yanjun Li

26 Example Class GradeBook’s constructor //in GradeBook.h GradeBook(int);
//in GradeBook.cpp GradeBook::GradeBook(int n) { setCourseNumber(n); } //in test.cpp GradeBook myGradeBook(2350); Spring 2010 CS1600 Yanjun Li

27 Default Constructor If you do not provide a constructor, the compiler provides a default constructor for you – a constructor with no parameters. You can also provide a default constructor explicitly. GradeBook::GradeBook() { setCourseNumber(1600); } Spring 2010 CS1600 Yanjun Li

28 Overloaded Constructors
Overloaded Functions: Functions having the same name but different sets of parameters. The parameter types The number of parameters The order of the parameter types Overloaded Constructors: Constructors with different sets of parameters. Spring 2010 CS1600 Yanjun Li

29 Constructor with Arguments vs. Default Constructor
If a constructor with parameters (arguments) is defined in a class, C++ will not implicitly create a default constructor for this class. If you want to have a default constructor, explicitly define it by yourself. Spring 2010 CS1600 Yanjun Li

30 The string Class A string represents a string of characters
An object of C++ Standard Library class std::string Defined in header file <string> Example: #include <string> Using std::string; : string nameOfCourse; Spring 2010 CS1600 Yanjun Li

31 Declaration and Initialization
A string variable can be declared with or without an initial value: Example: //s1 is initialized to the empty string string s1; //s2 is initialized to the string "hello" string s2("hello"); // s3 is initialized to the string "goodbye" string s3 = "goodbye"; Spring 2010 CS1600 Yanjun Li

32 Library function getline
Used to retrieve input until newline is encountered Defined in header file <string> Example: Inputs a line from standard input into string object nameOfCourse string nameOfCourse; getline( cin, nameOfCourse ); cin >> reads characters until the first white-space character is reached. Spring 2010 CS1600 Yanjun Li

33 A string Data Member In GradeBook class string courseName;
We add one more data member: string courseName; Add a pair of setter/getter member functions. Modify the constructors to initialize this data member as well. Spring 2010 CS1600 Yanjun Li

34 Comparing Two string Objects
Two strings can be compared using == string s1("abc"); string s2 = "abc"; if (s1 == s2) { } // yes! the two strings ARE equal Spring 2010 CS1600 Yanjun Li

35 Concatenate Two string Objects
Strings can be concatenated using the + operator string s1("hello"); string s2("goodbye"); string s3 = s1 + " and " + s2; //the value of s3 is "hello and goodbye" Spring 2010 CS1600 Yanjun Li

36 string Member Functions
length() and size() both return the number of characters in the string string s1; string s2 = "hello"; cout << s1.size(); // s1's size is 0 cout << s2.length(); // s2's size is 5 Spring 2010 CS1600 Yanjun Li

37 string Member Functions
substr(startIndex,length) returns specified substring within the string startIndex: The first position in a string is position 0. length of the substring. If the length specified is longer than the remaining number of characters, the rest of the string is used. Example: string s2 = "abcde uvwxyz"; s = s2.substr(1,4); //s is “bcde” s = s2.substr(1,50); //s is set to “bcde uvwxyz” Spring 2010 CS1600 Yanjun Li

38 Reference Reproduced from the Cyber Classroom for C++, How to Program, 5/e by Deitel & Deitel. Reproduced by permission of Pearson Education, Inc. Spring 2010 CS1600 Yanjun Li


Download ppt "Chapter 3 Introduction to Classes and Objects"

Similar presentations


Ads by Google