590 likes | 1.1k Views
Chapter 3 Introduction to Classes and Objects. C++, How to Program Deitel & Deitel. Basic Object Technology Concept. Objects: people, animals, plants, cars. We study objects’ attributes and observe objects’ behaviors . Dogs Attributes : name, color, breed, hungry, age
E N D
Chapter 3Introduction to Classes and Objects C++, How to Program Deitel & Deitel CS1600 Yanjun Li
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. CS1600 Yanjun Li
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. CS1600 Yanjun Li
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. CS1600 Yanjun Li
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. CS1600 Yanjun Li
Class • 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 CS1600 Yanjun Li
Question ? • To design a class, we should define attributes and behaviors. • Student class • Computer class • Customer class CS1600 Yanjun Li
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). CS1600 Yanjun Li
A C++ Class • In C++: • 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 CS1600 Yanjun Li
The Interface • The interface of a Class like amanual • 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 CS1600 Yanjun Li
Example: GradeBook Class • Data Member: int courseNumber; • Member function: void displayMessage(); • Header file: GradeBook.h classGradeBook { public: void displayMessage(); private: int courseNumber; }; CS1600 Yanjun Li
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. CS1600 Yanjun Li
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. CS1600 Yanjun Li
#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 CS1600 Yanjun Li
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; } CS1600 Yanjun Li
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. CS1600 Yanjun Li
Memory courseNumber Space for data member of object myGradeBook Use GradeBook Class • Create a GradeBook object • GradeBook myGradeBook; • className objectName; CS1600 Yanjun Li
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.); CS1600 Yanjun Li
Driver File • Driver files • 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; } CS1600 Yanjun Li
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 CS1600 Yanjun Li
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 CS1600 Yanjun Li
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. CS1600 Yanjun Li
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; } CS1600 Yanjun Li
Get Functions • Get the value of a data member. • Example: //in GradeBook.h int getCourseNumber( ); //in GradeBook.cpp int GradeBook::getCourseNumber( ) { return couresNumber; } CS1600 Yanjun Li
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. CS1600 Yanjun Li
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); CS1600 Yanjun Li
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); } CS1600 Yanjun Li
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. CS1600 Yanjun Li
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. CS1600 Yanjun Li
The stringClass • A stringrepresents 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; CS1600 Yanjun Li
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"; CS1600 Yanjun Li
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 objectnameOfCourse string nameOfCourse; getline( cin, nameOfCourse ); • cin >> reads characters until the first white-space character is reached. CS1600 Yanjun Li
A string Data Member • In GradeBook class • 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. CS1600 Yanjun Li
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 CS1600 Yanjun Li
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" CS1600 Yanjun Li
stringMember 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 CS1600 Yanjun Li
stringMember 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” CS1600 Yanjun Li
Reference • Reproduced from the Cyber Classroom for C++, How to Program, 5/e by Deitel & Deitel. • Reproduced by permission of Pearson Education, Inc. CS1600 Yanjun Li