Unformatted text preview:

Using C++ Classes / page 1Using 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. E.g. 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 ("."), E.g.Copying from one class object to another by default does a bit-wise copy, such as D. 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 private.3. Access specifiers may be listed multiple times, though good style dictates that all public members are given first, then private.class class-name {member-list};class Point {public:int GetX(); // Returns the value of x.void SetX(); // Sets the value of x.private:int x; // x-coordinateint y; // y-coordinate};Point P; // Note this is different than Point P();P.SetX( 300 );cout << "x-coordinate is: " << P.GetX();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 (e.g. GetX)2. Mutator functions (e.g. SetX)3. Operators that let you define C++ operators for each class object (e.g. move a point)4. Iterators that process a collection of objects (e.g. 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. E.g.1. 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 correspondance.2. 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 documentation.class 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. Note y fcns. not shown}; //End of Point classclass Point {public:void SetX(int xval); // Sets value of X....private:int x; // x-coordinate...}; //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. E.g.So 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 0.2. 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. E.g.where 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. Using the Accessor & Mutator functions is better since:(1). It allows us to later change the private data (e.g. 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,0Point B(3); // initialized to 3,0Point C(3,5); // initialized to 3,5Using 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. I. Array of Class ObjectsThe constructor for each member is called upon definition of the array, E.g.calls 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 (~). E.g.Point P;Point Q(P);Point Z = P;Point::Point( const Point & p2){x = p2.x;y = p2.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. 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


View Full Document

UIC CS 340 - Using Classes in C++

Documents in this Course
Load more
Download Using Classes in C++
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Using Classes in C++ and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Using Classes in C++ 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?