class miscellanea details about classes. review we’ve seen that a class has two sections: class...

25
Class Miscellanea Class Miscellanea Details About Classes Details About Classes

Upload: bonnie-carson

Post on 14-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Class MiscellaneaClass Miscellanea

Details About ClassesDetails About Classes

Page 2: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

ReviewReview

We’ve seen that a class has two sections:We’ve seen that a class has two sections:class Temperature{ public: // ... public members private: // ... private members};

Anything that should be accessible to users of the class should be declared in the Anything that should be accessible to users of the class should be declared in the public sectionpublic section..

Anything else should be declared in the Anything else should be declared in the private sectionprivate section..

Page 3: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Private MembersPrivate MembersThe private section should contain a class’s The private section should contain a class’s datadata, plus any “utility” function members useful , plus any “utility” function members useful

for implementing the class’s function members, but inappropriate for outside users.for implementing the class’s function members, but inappropriate for outside users.

class Temperature{ public: private: int Compare(const Temperature & temp2) const;

double myMagnitude; char myScale;};

Page 4: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Object StateObject State

Each class object has its own copy of each data member.Each class object has its own copy of each data member.

Temperature temp1(212, ‘F’), temp2(100, ‘C’);

An object’s data members’ values make up its An object’s data members’ values make up its statestate..

Each object can have a distinct state.Each object can have a distinct state.

F

myMagnitude

myScale

temp1 212

C

myMagnitude

myScale

temp2 100

Page 5: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Class ScopeClass Scope

A class member (data or function) can be directly A class member (data or function) can be directly accessed by any class accessed by any class functionfunction membermember or or friendfriend..

// memberinline char Temperature::Scale() const{ return myScale; // private access}

Class friends are Class friends are notnot function members, but are “normal” functions function members, but are “normal” functions with permission to access the private section.with permission to access the private section.

// friendinline istream & operator>>(istream & in, Temperature & temp){ in >> myMagnitude >> myScale;}

Page 6: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Public MembersPublic MembersThe public section should contain a class’s The public section should contain a class’s operationsoperations..

class Temperature{ public: Temperature(); Temperature(double magnitude, char scale); double Magnitude() const; char Scale() const; Temperature Fahrenheit() const; Temperature Celsius() const; Temperature Kelvin() const; friend istream & operator>>(istream & in, Temperature & temp); friend ostream & operator<<(ostream & out, const Temperature & temp); private: // ... private members};

Page 7: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Class InterfaceClass InterfaceThe public operations (and a few default ones) make up the The public operations (and a few default ones) make up the interfaceinterface, or way that a , or way that a

program can use the class.program can use the class.

#include “Temperature.h”// ...

Temperature temp1; // declare cin >> temp1; // input double itsMagnitude = temp1.Magnitude(); // read char itsScale = temp1.Scale(); // members Temperature temp2 = temp1.Kelvin(); // convert cout << temp2; // output

Page 8: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Interfaces (Ct’d)Interfaces (Ct’d)

With a few exceptions, an operation not in a class’s With a few exceptions, an operation not in a class’s interface cannot be applied to a class object.interface cannot be applied to a class object.

if (temp1 == temp2) // error! // ...

Since operator== is not defined for Temperature objects, the Since operator== is not defined for Temperature objects, the compiler has no means of knowing how they should be compiler has no means of knowing how they should be compared. compared.

Temperature temp1(212, ‘F’), temp2(100, ‘C’);

if (temp1 == temp2) // true or false?

Page 9: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

UtilitiesUtilities

int Temperature::Compare(const Temperature & t2) const{ Temperature leftTemp = Kelvin() // me in K Temperature rightTemp = t2.Kelvin(); // t2 in K

return left.Magnitude() - right.Magnitude();}

We can always implement such operations ourselves.We can always implement such operations ourselves.

If we first define a nifty utility function to compare myself with another If we first define a nifty utility function to compare myself with another Temperature object:Temperature object:

Compare() returns:Compare() returns:– 0 if I am equal to t2, 0 if I am equal to t2,

– a negative value if I am less-than t2, and a negative value if I am less-than t2, and

– a positive value if I am greater than t2.a positive value if I am greater than t2.

Page 10: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

OperationsOperations

bool Temperature::operator==(const Temperature & temp2){ return Compare(temp2) == 0; // true iff I == temp2}

Then we can easily define the relational operators:Then we can easily define the relational operators:

bool Temperature::operator!=(const Temperature & temp2){ return Compare(temp2) != 0; // true iff I != temp2}

bool Temperature::operator<(const Temperature & temp2){ return Compare(temp2) < 0; // true iff I < temp2}

// ...

Page 11: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

AssignmentAssignmentFor any user-defined class, C++ provides a For any user-defined class, C++ provides a

default assignment operatordefault assignment operator (operator=). (operator=).#include “Temperature.h”// ...

Temperature temp, saveTemp; cin >> temp; saveTemp = temp; // default assignment // ...

This default operation simply This default operation simply copies the memberscopies the members of the object of the object to the right of the = into the members of the object to the to the right of the = into the members of the object to the left of the =. left of the =.

Page 12: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

A ProblemA ProblemA program can consist of multiple files.A program can consist of multiple files.

Suppose a programmer (or programming team) unwittingly #includes a class in two different places?Suppose a programmer (or programming team) unwittingly #includes a class in two different places?

When main.h is compiled, an error will be When main.h is compiled, an error will be generated, because the declaration of generated, because the declaration of SomeClassSomeClass will be compiled more than will be compiled more than once.once.

class SomeClass{ // ...};

SomeClass.h

#include “SomeClass.h”class AnotherClass{ // ...};

AnotherClass.h

#include “SomeClass.h”#include “AnotherClass.h”int main(){ // ...};

main.h

Page 13: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

An Ugly SolutionAn Ugly Solution

#ifndef TEMPERATURE#define TEMPERATURE

// ... #include directives

class Temperature{ // ... details omitted};

// ... inline definitions

#endif

The solution is to use a new directive named The solution is to use a new directive named #ifndef and and “wrap” the class declaration as follows:“wrap” the class declaration as follows:

When an When an #ifndef directive directive is processed, if the is processed, if the identifer following it is identifer following it is notnot defined, compilation defined, compilation proceeds normally.proceeds normally.

But if it But if it isis defined, then all defined, then all subsequent code is subsequent code is skippedskipped until a until a #else, , #elif, or , or #endif directive appears.directive appears.

Page 14: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

An Ugly SolutionAn Ugly Solution

#ifndef TEMPERATURE#define TEMPERATURE

// ... #include directives

class Temperature{ // ... details omitted};

// ... inline definitions

#endif

The solution is to use a new directive named The solution is to use a new directive named #ifndef and and “wrap” the class declaration as follows:“wrap” the class declaration as follows:

So the first time the file is So the first time the file is processed, TEMPERATURE processed, TEMPERATURE is undefined, and execution is undefined, and execution proceeds as usual.proceeds as usual.

The first thing following the The first thing following the #ifndef is a is a #define directive that defines the directive that defines the identifier TEMPERATURE.identifier TEMPERATURE.

The class declaration is then The class declaration is then processed normally.processed normally.

Page 15: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

An Ugly SolutionAn Ugly Solution

#ifndef TEMPERATURE#define TEMPERATURE

// ... #include directives

class Temperature{ // ... details omitted};

// ... inline definitions

#endif

The solution is to use a new directive named The solution is to use a new directive named #ifndef and and “wrap” the class declaration as follows:“wrap” the class declaration as follows:

The second the file is The second the file is processed, TEMPERATURE processed, TEMPERATURE is defined, and everything is defined, and everything between there and the between there and the #endif is skipped. is skipped.

While it isn’t elegant, this While it isn’t elegant, this ensures that the class ensures that the class declaration is processed declaration is processed just once, regardless of just once, regardless of what programmers do.what programmers do.

Page 16: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

The Bottom LineThe Bottom LineIt is “good form” to It is “good form” to alwaysalways wrap a class declaration this way, using the uppercase wrap a class declaration this way, using the uppercase

name of the class:name of the class:

This will prevent This will prevent SomeClassSomeClass (or (or AnotherClassAnotherClass) ) from being declared more than once, from being declared more than once, regardless of what a programmer does.regardless of what a programmer does.

#ifndef SOME_CLASS#define SOME_CLASSclass SomeClass{ // ...};#endif

SomeClass.h

#ifndef ANOTHER_CLASS#define ANOTHER_CLASS#include “SomeClass.h”class AnotherClass{ // ...};#endif

AnotherClass.h

#include “SomeClass.h”#include “AnotherClass.h”int main(){ // ...};

main.h

Page 17: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

A Final DetailA Final Detail

class Temperature{ // ... private: double myMagnitude; char myScale;};

The classes we have seen thus far have “normal” data members: The classes we have seen thus far have “normal” data members:

Each class object has its own “local” data members:Each class object has its own “local” data members:

F

myMagnitude

myScale

temp1 212

C

myMagnitude

myScale

temp2 100

Page 18: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

QuestionQuestionSuppose we want Suppose we want class Temperatureclass Temperature to keep track of to keep track of

how many Temperature objects have been declared?how many Temperature objects have been declared?

One way to do so is to use a One way to do so is to use a static data memberstatic data member: :

class Temperature{ public: private: double myMagnitude; char myScale; static int tempCounter;};

int Temperature::tempCounter = 0;

Static data members must be initialized Static data members must be initialized externallyexternally (outside of the constructor), in the manner shown.(outside of the constructor), in the manner shown.

Page 19: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

ConstructorsConstructorsEach constructor can then increment this counter, so that each new Each constructor can then increment this counter, so that each new Temperature will be counted: will be counted:

inline Temperature::Temperature(){ myMagnitude = 0.0; myScale = ‘C’; tempCounter++;}

inline Temperature::Temperature(double magnitude, char scale){ // ... validity-checking omitted myMagnitude = magnitude; myScale = scale; tempCounter++;}

Page 20: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Static MembersStatic MembersWe can then add a We can then add a Count() function member to display the value of this function member to display the value of this

counter:counter:

inline int Temperature::Count() const{ return tempCounter;}

Now, the expression:Now, the expression:cout << Temperature::Count() << endl;

will display the number of will display the number of Temperature objects currently in existence. objects currently in existence.

Static members are sometimes called Static members are sometimes called class variablesclass variables because they because they belong to the classbelong to the class, not its objects., not its objects.

Page 21: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

DestructorsDestructors

class Temperature{ public: // ... ~Temperature(); private: // ...};

inline Temperature::~Temperature(){ tempCounter--;}

To remain accurate, our counter must be To remain accurate, our counter must be decrementeddecremented each time a each time a Temperature is destroyed. is destroyed.

To do this, we can add a To do this, we can add a destructor functiondestructor function, whose name is the name of the class preceded by tilde (~): , whose name is the name of the class preceded by tilde (~):

Page 22: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Destructor DetailsDestructor DetailsAn object’s destructor is called at the end of its scope.An object’s destructor is called at the end of its scope.

Like a constructor, a destructor has Like a constructor, a destructor has no return-typeno return-type..

Unlike a constructor, a destructor can have Unlike a constructor, a destructor can have no parametersno parameters so it so it cannot be overloadedcannot be overloaded with multiple definitions ( with multiple definitions (a class can a class can have only one destructor functionhave only one destructor function).).

Destructors are only needed when some action is needed (often “cleanup”) at the end of an object’s lifetime, such as Destructors are only needed when some action is needed (often “cleanup”) at the end of an object’s lifetime, such as ensuring the consistency of a static member, deallocating memory allocated by a constructor, and so on.ensuring the consistency of a static member, deallocating memory allocated by a constructor, and so on.

Page 23: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

SummarySummary

Data members can be “normal” or static.Data members can be “normal” or static.– Normal data members are local to each class object.Normal data members are local to each class object.

– Static data members are shared by all class objects.Static data members are shared by all class objects.

Data members should be declared as Data members should be declared as privateprivate..

Function members can be declaredFunction members can be declared– private, for utility functionsprivate, for utility functions

– public, for operations on the classpublic, for operations on the class

The public operations on a class make up its The public operations on a class make up its interfaceinterface..

Page 24: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Summary (Summary (Ct’dCt’d))

To avoid “redeclaration” errors, “wrap” every class:To avoid “redeclaration” errors, “wrap” every class:

#ifndef CLASS_NAME#define CLASS_NAME

// ... #include directives

class ClassName{ // ... details omitted};

// ... inline definitions

#endif

and the class declaration will only be processed once.and the class declaration will only be processed once.

Page 25: Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private:

Summary (Summary (Ct’dCt’d))

A class destructor is a function member:A class destructor is a function member:

– that has no return-type (like a constructor)that has no return-type (like a constructor)

– whose name is the name of the class whose name is the name of the class preceded by a tilde (~)preceded by a tilde (~)

– that is called automatically at the end of an that is called automatically at the end of an object’s lifetimeobject’s lifetime

– that is only needed when some action must that is only needed when some action must be taken at the end of an object’s lifetime.be taken at the end of an object’s lifetime.