[PDF] structo crete screws
[PDF] structural analysis 1 pdf notes
[PDF] structural design patterns pdf
[PDF] structural explanation of health inequalities
[PDF] structural formula of carboxylic acid
[PDF] structural functionalism in family
[PDF] structural organisation of proteins pdf
[PDF] structural queries
[PDF] structural queries in information retrieval
[PDF] structure and function of nucleic acids pdf
[PDF] structure and union in c geeksforgeeks
[PDF] structure de données pdf
[PDF] structure de l'atome cours 3ème pdf
[PDF] structure électronique de l'atome cours pdf
[PDF] structure exercises in c
CHAPTER
3CLASSES
class head struct unionclass name class identifier base spec
3.1Classes and Objects
3.2Sample Application: A
Stack Class
3.3Efciency and RobustnessIssues for Classes andObjects
3.4Sample Application: ATime Stamp Class
3.5Constructors and theDestructor
3.6Sample Application: A Task
Class
3.7Class Data Members andMethods
3.8Pointers to Objects
Common Programming
Errors
Programming Exercises
3.1 / CLASSES AND OBJECTS99
3.1CLASSES AND OBJECTS
This chapter examines the foundations of object-oriented programming in C++. Because object-oriented programming in any language begins with classes, we begin with the C++ syntax for declaring a class.
Class Declarations
In C++, a class is a data type. Standard C++ has built-in classes such asstring, and programmers can extend the language by creating their own class data types. Aclass declarationcreates a class as a data type. The declaration describes the data members and methods encapsulated in the class.
EXAMPLE 3.1.1.The class declaration
class Human { //... data members and methods go here creates the classHuman. The declarationdescribesthe data members and methods that characterize a
Human.
In the declaration, the term
classis a keyword. The termHumanis sometimes called theclass tag; the tag is the identier or name of the data type created by the declaration. Note that a semicolon follows the closing brace in the class declaration; the semicolon is required.
Given our declaration of
Human, the statement
Human maryLeakey; // create an object
denes a variablemaryLeakeyof typeHuman. Just as the statement int x; // built-in type int denes anintvariable, so
Human maryLeakey; // user-defined type Human
denes aHumanvariable. In C++, a variable of aclassdata type such asHumanis an objectin the sense of object-oriented programming.
100CHAPTER 3 / CLASSES
A class declaration must comebeforethe denition of any class objects. In Exam- ple 3.1.1, the declaration of Humantherefore comes before the denition ofmaryLeakey as aHumanobject. By the way, note that the keywordclassisnotrequired indening objects. Given the class declaration forHumanin Example 3.1.1, the denitions
Human maryLeakey; // usual style
class Human fred; //*** legal but unusual style both deneHumanobjects.
Given the declaration of
Humanin Example 3.1.1, we can dene either stand-alone Humanobjects such asmaryLeakeyor arrays ofHumanobjects. EXAMPLE 3.1.2.Given the declaration of classHumanin Example 3.1.1, the code segment
Human latvians[ 3600000 ];
denes an arraylatviansthat has 3,600,000 elements, each of typeHuman. The C++ class extends the Cstructure. Indeed, the keywordstruct, when used in
C++, creates a
class.
EXAMPLE 3.1.3.The class declaration
struct Human { //... data members and methods go here creates the classHuman, even though the keywordstructis used instead of the keyword class. Although either of the keywordsclassandstructmay be used to declare a C++ class, the two do differ signicantly with respect to the default information hidingthat the class supports.
Information Hiding in C++
The C++ keywordprivatecan be used tohideclass data members and methods, and the keyword publiccanbeusedtoexposeclassdatamembersandmethods. (C++alsohasthe keyword protectedforinformationhiding; seeChapter4.) Inthespiritofobject-oriented design, we can use privateto hide the classimplementationandpublicto expose the class interface.
EXAMPLE 3.1.4.The class declaration
class Person { public: void setAge( unsigned n ); unsigned getAge() const; private: unsigned age;
3.1 / CLASSES AND OBJECTS101
creates aPersonclass whose interface consists of twopublicmethods,setAgeand getAge, and whose implementation consists of anunsigneddata memberage.A colon :follows the keywordsprivateandpublic. The keywordpublicoccurs rst in our example, although the example could have been written as class Person { private: unsigned age; public: void setAge( unsigned n ); unsigned getAge() const; or even as class Person { public: void setAge( unsigned n ); private: unsigned age; public: unsigned getAge() const; The last version is not good style but shows that theprivateandpublicclass members may be intermixed within the class declaration.
The keyword
constin the declaration ofgetAgesignals that this method, unlike method For now, the basic syntax and the underlying idea are important.
Clients of the
Personclass can request services by invoking thesetAgeand getAgemethods, which arepublic; but clients have no access to the implementation data member age, which isprivate. The next example shows how the methods can be invoked. Our classdeclaration containsmethod declarationsforsetAgeandgetAge. The methoddeclarationsprovidethefunctionprototypesforthemethods. Thetwomethods need to be dened, but we have not yet provided the denitions. We do so shortly.
The Member Selector Operator
Access to any class member, whether data member or method, is supported by themember selector operator .and theclass indirection operator->.
EXAMPLE 3.1.5.The code segment
class Person { public: void setAge( unsigned n ); unsigned getAge() const;
102CHAPTER 3 / CLASSES
private: unsigned age; int main() {
Person boxer;
boxer.setAge( 27 ); //... remainder of main's body illustrates the use of.to select members. Inmainwe rst deneboxeras aPerson object and then invoke itssetAgemethod boxer.setAge( 27 ); The member selector operator occursbetweenthe class objectboxerand the class member, in this case the method setAge. The member selector operator is used to access either data members or methods. How- ever, recall that a client has access only to a class's publicmembers, whether they be data members or methods.
EXAMPLE 3.1.6.The program
#include
using namespace std; class Person { public: void setAge( unsigned n ); unsigned getAge() const; private: unsigned age; int main() { Person boxer;
boxer.setAge( 27 ); cout << boxer.age << '\n'; //*** ERROR: age is private return 0; contains an error becausemaintries to accessage,aprivatedata member in the Personclass. OnlyPersonmethods such assetAgeandgetAgehave access to its privatemembers. To be precise,privatemembers can be accessed only by class methods orfriendfunctions, which are explained in Chapter 6. 3.1 / CLASSES AND OBJECTS103
Class Scope
A class'sprivatemembers haveclass scope; that is,privatemembers can be accessed onlyby class methods. EXAMPLE 3.1.7.The class declaration
class C { public: void m(); // public scope private: char d; // class scope (private scope) we call public scopebecause, as apublicmember, it can be accessed from outside the class. In C++, class scope is thedefaultfor members when the class is declared with the keyword class. In this case, members default toprivateif the keywordspublicor protected(see Chapter 4) are not used. EXAMPLE 3.1.8.The class declaration
class Z { int x; is equivalent to class Z { private: int x; In the rst case,xdefaults toprivate. In the second case,xoccurs in a region of the declaration explicitly labeled private. Our style is to put thepublicmembers rst inside a declaration because this forces us then to use the label private, which adds clarity to the declaration. Besides, thepublic members constitute the class's interface and, in this sense, deserve to come rst. The principle of information hiding encourages us to give the class's implementation, particularly its data members, class scope. Restricting data members to class scope is likewise a key step in designing classes as abstract data types. The Difference between the Keywordsclassandstruct
is used, then all members default toprivate.Ifstructis used, then all members default to public. 104CHAPTER 3 / CLASSES
EXAMPLE 3.1.9.In the declaration
class C { int x; void m(); data memberxand methodmdefault toprivate. By contrast, in the declaration struct C { int x; void m(); both default topublic. Whichever keyword is used, objects of typeCmay be dened in the usual way: C c1, c2, carray[ 100 ];
EXAMPLE 3.1.10.The declaration
class C { int x; // private by default public: void setX( int X ); // public is equivalent to struct C { void setX( int X ); // public by default private: int x; in that each declaration makesxaprivatedata member andmapublicmethod. Our examples typically useclassto emphasize the object-oriented principle of infor- mation hiding: a class's members default to privateunless they are explicitly selected as part of its publicinterface. Dening Class Methods
Some earlier examples use the class declaration
class Person { public: void setAge( unsigned n ); unsigned getAge() const; private: unsigned age; 3.1 / CLASSES AND OBJECTS105
whichdeclaresbut does notdenethe methodssetAgeandgetAge. Class methods may be dened in two ways: A method may be
declared insidethe class declaration butdened outsidethe class declaration. A method may be
dened insidethe class declaration. Such a denition is said to be inline, a C++ keyword. Aninlinedenition also serves as a declaration. We use two examples to clarify the distinction.
EXAMPLE 3.1.11.The code segment
class Person { public: void setAge( unsigned n ); unsigned getAge() const; private: unsigned age; // define Person's setAge void Person::setAge( unsignedn){ age=n; // define Person's getAge unsigned Person::getAge() const { return age; side the class declaration. The denitions use the scope resolution operator ::because many classes other than Personmight have methods namedsetAgeandgetAge.In
addition, there might be top-level functions with these names. EXAMPLE 3.1.12.The code segment
class Person { public: void setAge( unsignedn){age=n;} unsigned getAge() const { return age; } private: unsigned age; 106CHAPTER 3 / CLASSES
denesPerson's methods inside the class declaration. The methods are therefore inline. An inline denition recommends to the compiler that the method's body be placed wherever the method is invoked so that a function call does not occur in the translated code. For example, if the compiler heeds the recommendation to make setAgeinline, then a code segment such as Person singer;
singer.setAge( 33 ); // compiler: please make inline! would be translated so that the code forsetAge's body would be placed where the call to setAgeoccurs. A function may be dened inline even if its denition occursoutsidethe class decla- ration by using the keyword inlinein a method declaration. EXAMPLE 3.1.13.In the code segment
class Person { public: inline void setAge( unsigned n );quotesdbs_dbs17.pdfusesText_23