Example: biology

Using Classes in C++ - dalereed

Using C++ Classes / page 1 Using Classes in C++Note: Many of the examples given below are taken from the Irvine bookI. Creating Classes A. An Example [from Deitel & Deitel]: structs vs. classesDrawbacks to Using a struct:1. Initialization not specifically required, and may be done incorrectly2. Invalid values can be assigned to struct members (as in example)3. If struct implementation changes, all the programs Using the struct must also change4. Structs aren t first- class : they cannot be printed as a unit or compared B. class DefinitionBasic form is: class name has file scope and external linkage. Point class for points on a 2D cartesian graph:Keywords public and private are access specifiers. Note that storage is not allocated until an instance of the class is created (there is also an access specifier protected, which we will avoid for now) C. class ObjectsGeneral format is: class -name identifier. We can access class methods Using the dot operator ("."), from one class object to another by default does a bit-wise copy, such as D.

Using C++ Classes / page 3 H. Constructors A constructor is a special-purpose member function that is automatically executed when a class object is created. [Irvine] The constructor always has the sa me name as its class, with no return type.

Tags:

  Using, Classes, Class, Using classes in c

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of Using Classes in C++ - dalereed

1 Using C++ Classes / page 1 Using Classes in C++Note: Many of the examples given below are taken from the Irvine bookI. Creating Classes A. An Example [from Deitel & Deitel]: structs vs. classesDrawbacks to Using a struct:1. Initialization not specifically required, and may be done incorrectly2. Invalid values can be assigned to struct members (as in example)3. If struct implementation changes, all the programs Using the struct must also change4. Structs aren t first- class : they cannot be printed as a unit or compared B. class DefinitionBasic form is: class name has file scope and external linkage. Point class for points on a 2D cartesian graph:Keywords public and private are access specifiers. Note that storage is not allocated until an instance of the class is created (there is also an access specifier protected, which we will avoid for now) C. class ObjectsGeneral format is: class -name identifier. We can access class methods Using the dot operator ("."), from one class object to another by default does a bit-wise copy, such as D.

2 Controlling Member AccessA member may be either a function or a data item1. Access specifiers:a. public: non-member function can access these membersb. private: member of same class only can access these membersc. protected: same as private, only derived Classes can access these members2. If no access specifier is given, the default is Access specifiers may be listed multiple times, though good style dictates that all public members are given first, then class -name {member-list}; class Point {public:int GetX(); // Returns the value of SetX(); // Sets the value of :int x; // x-coordinateint y; // y-coordinate};Point P; // Note this is different than Point P(); ( 300 );cout << "x-coordinate is: " << ();Point P1, P2;..P2 = P1; Using C++ Classes / page 2 E. Example: the Point classShort functions as shown above may be given all on one line. F. Types of Member functions1. Accessor, or selector functions ( GetX)2. Mutator functions ( SetX)3.

3 Operators that let you define C++ operators for each class object ( move a point)4. Iterators that process a collection of objects ( recompute each Account balance) G. Inline and Out-of-line definitionsRather than list a member function definition along with the declaration under the public access specifier, we can leave the member function declaration as public but hide the imple-mentation details. The binary scope resolution operator "::" specifies that Setx corresponds to the Point class . It can access the private data members only because it has this The member function SetX must specify the type of parameters, though parameter names need not be given. (In fact, given parameter names need not be the same as in the definition) Since this declaration specifies the interface, it is a good idea to provide the parameter names as well as brief Point {public:int GetX() // Returns value of X{return x; }.void SetX( int xval) // Sets value of X{ x = xval; } private:int x; // x-coordinateint y; // y-coordinate.}

4 Note y fcns. not shown}; //End of Point classclass Point {public:void SetX(int xval); // Sets value of :int x; // }; //End of Point classvoid Point::Setx( int xval){return x;} Using C++ Classes / page 3 H. ConstructorsA constructor is a special-purpose member function that is automatically executed when a class object is created. [Irvine] The constructor always has the same name as its class , with no return type. 1. A constructor with no parameters is called a default constructor. now when executing your program, the declaration Point aPoint; has the effect of creating a point instance called aPoint with its x & y data members initialized to Alternate & Overloaded constructorsWe can have more than one constructor, where we also provide parameters to initialize an object s data members, optionally giving default values. in the main part of your program you could then have:a. Rather than SetX( xval) we could simply have x=xval, since member functions have access to private data members.

5 Using the Accessor & Mutator functions is better since:(1). It allows us to later change the private data ( rename x to pointx) without worrying about any side-effects within the class implementa-tion.(2). It allows us to later implement validity checks on member data valuesb. See examples of RogueWave date constructorsclass Point {public:Point() // Default constructor{x = 0;y = 0;}private:int x;int y;}; //End of Point classPoint::Point( int xval=0; int yval=0){SetX( xval);SetY( yval);}Point A; // initialized to 0,0 Point B(3); // initialized to 3,0 Point C(3,5); // initialized to 3,5 Using C++ Classes / page 43. Copy constructorsA copy constructor is automatically called anytime an object is passed by value. It makes a local copy of the object, making a bitwise copy by default (the system makes a default constructor). a. Both declarations of Q and Z below result in a call to the copy constructor:where the copy constructor could look like:The reference parameter is const qualified so that the original is unchanged.

6 I. Array of class ObjectsThe constructor for each member is called upon definition of the array, the Point constructor for each of the 3 members. J. Destructors1. This special function is automatically called when a class object is deleted. This can happen in these situations:a. An object has local scope and goes out of scopeb. An object has file scope and the main program endsc. An object was dynamically allocated ( Using new) and is now deleted ( Using delete)2. The name of a destructor is the class name preceeded by a tilde (~). P;Point Q(P);Point Z = P;Point::Point( const Point & p2){x = ;y = ;}Point figure[ 3]; class Point {public:~Point() { cout<< "Point destructor called\n"; }..}; // End of class PointUsing C++ Classes / page 5II. Miscellaneous A. The ability to have objects be "1st- class " in C++ is not automatic. The different aspects of an object being first class must be implemented by the user. This includes constructors, destruc-tors, overloading output & input operators, overloading other operators, the copy constructor.

7 Functions must be written for each of these. B. class scope1. class data members and member functions are immediately accessible by that class s member functions simply by name2. If a member function defines a variable with the same name as a variable with class scope, the class -scope variable is hidden. C. Difference between constructor and a function callGiven the code below:Note that compiler must check arguments to tell the difference betweenDate d4( 24, 2, 97)and the function declarationDate d4( int, int, int);where the typenames tell the compiler that this is a prototypeclass Date {public:Date ();Date(int d, int m=0, int y=0);private:int day, month, year;};Date::Date() //Default constructor{day = 0, month = 0; year = 0;}Date::Date(int d, int m, int y)//Constructor{day = d; month = m, year = y;}int main(){Date d1; // Default constructorDate d2(2);Date d3(24,2);Date d4(24,2,97);Date d5(); // Function }Date d5() //Function definition{return Date( 24, 2, 97);} Using C++ Classes / page 6 D.

8 Preventing multiple inclusions of a header file#ifndef TIME1_H#define #endif E. delete - make sure you use [] with delete if it is a dynamic array. This way it calls the destruc-tor for you properly. F. References and Pointers1. A reference parameter means the parameter may be changed2. A reference variable essentially is the object it is *arrayPtr;arrayPtr = new int[ 100]; // Dynamic [] arrayPtr;// , Deitel & Deitel// Demonstrating the class member access operators . and ->#include < > class Count { // Simple class Countpublic: int x; void print() { cout << x << '\n'; }};main(){ Count counter, // create counter object *counterPtr = &counter, // pointer to counter &counterRef = counter; // reference to counter cout << "Assign 7 to x and print Using the object's name: "; = 7; // assign 7 to data member x (); // call member function print cout << "Assign 8 to x and print Using a reference: "; = 8; // assign 8 to data member x (); // call member function print cout << "Assign 10 to x and print Using a pointer: "; counterPtr->x = 10; // assign 10 to data member x counterPtr->print(); // call member function print return 0;}/* --------- Output ------------Assign 7 to x and print Using the object's name: 7ssign 8 to x and print Using a reference: 8 Assign 10 to x and print Using a pointer: 10*/ Using C++ Classes / page 7 G.

9 Constructors are called when object enters scope. Destructor called when it exits scope. objects exist until program , Deitel & Deitel, Constructors & destructors order#include < > class CreateAndDestroy {public: CreateAndDestroy(int); // constructor ~CreateAndDestroy(); // destructorprivate: int data;};CreateAndDestroy::CreateAndDestro y(int value){ data = value; cout << "Object " << data << " constructor";}CreateAndDestroy::~CreateA ndDestroy() { cout << "Object " << data << " destructor " << endl; }void create(void) // Function to create objects{ CreateAndDestroy fifth(5); cout << " (local automatic in create)\n"; static CreateAndDestroy sixth(6); cout << " (local static in create)\n"; CreateAndDestroy seventh(7); cout << " (local automatic in create)\n";}CreateAndDestroy first(1); // global objectmain(){ cout << " (global created before main)\n"; CreateAndDestroy second(2); // local object cout << " (local automatic in main)\n"; static CreateAndDestroy third(3).}

10 // local object cout << " (local static in main)\n"; create(); // call function to create objects CreateAndDestroy fourth(4); // local object cout << " (local automatic in main)\n"; return 0;} /* Output starts on line below Object 1 constructor (global created before main)Object 2 constructor (local automatic in main)Object 3 constructor (local static in main)Object 5 constructor (local automatic in create)Object 6 constructor (local static in create)Object 7 constructor (local automatic in create)Object 7 destructor Object 5 destructor Object 4 constructor (local automatic in main)Object 4 destructor Object 2 destructor Object 3 destructor Object 1 destructor Object 6 destructor */ Using C++ Classes / page 8 H. Returning a reference to a private data It may be desireable to return a reference, such as when we want to use the return value on the left-hand side (l-value) of an assignment or when we want to chain assignments together such as in A=B=C; 2.


Related search queries