short review of c++

49
Review of C++ Programming Part II Sheng-Fang Huang

Upload: ifat-nix

Post on 27-Sep-2015

220 views

Category:

Documents


0 download

DESCRIPTION

A brief introduction to C++ programming language

TRANSCRIPT

  • Review of C++ ProgrammingPart IISheng-Fang Huang

  • Composition: Objects as Members of ClassesCompositionA class can have objects of other classes as membersExampleAlarmClock object with a Time object as a memberA common form of software reusability is composition, in which a class has objects of other classes as members.

  • Composition: Objects as Members of ClassesInitializing member objectsMember initializers pass arguments from the objects constructor to member-object constructorsIf a member initializer is not providedA compilation error occurs if the member objects class does not provide any proper constructor.

  • 1// Fig. 10.10: Date.h

    2// Date class definition; Member functions defined in Date.cpp

    3#ifndef DATE_H

    4#define DATE_H

    5

    6class Date

    7{

    8public:

    9 Date( int = 1, int = 1, int = 1900 ); // default constructor

    10 void print() const; // print date in month/day/year format

    11 ~Date(); // provided to confirm destruction order

    12private:

    13 int month; // 1-12 (January-December)

    14 int day; // 1-31 based on month

    15 int year; // any year

    16

    17 // utility function to check if day is proper for month and year

    18 int checkDay( int ) const;

    19}; // end class Date

    20

    21#endif

  • 1// Fig. 10.11: Date.cpp

    2// Member-function definitions for class Date.

    3#include

    4using std::cout;

    5using std::endl;

    6

    7#include "Date.h" // include Date class definition

    8

    9// constructor confirms proper value for month; calls

    10// utility function checkDay to confirm proper value for day

    11Date::Date( int mn, int dy, int yr )

    12{

    13 if ( mn > 0 && mn

  • 29

    30// print Date object in form month/day/year

    31void Date::print() const

    32{

    33 cout

  • friendTo declare a function as a friend of a class:Provide the function prototype in the class definition preceded by keyword friend.To declare a class as a friend of a class:Place a declaration of the form friend class ClassTwo; in the definition of class ClassOneAll member functions of class ClassTwo are friends of class ClassOne

  • friend ClassesFriendship is granted, not takenFor class B to be a friend of class A, class A must explicitly declare that class B is its friendFriendship relation is neither symmetric nor transitiveIf class A is a friend of class B, and class B is a friend of class C, you cannot infer that class B is a friend of class A, that class C is a friend of class B, or that class A is a friend of class C Place all friendship declarations first inside the class definitions body and do not precede them with any access specifier.

  • Dynamic Memory Management with Operators new and deleteDynamic memory managementEnables programmers to allocate and deallocate memory for any built-in or user-defined typePerformed by operators new and deleteFor example, dynamically allocating memory for an array instead of using a fixed-size array

  • Dynamic Memory Management with Operators new and deleteOperator newAllocates (i.e., reserves) storage of the proper size for an object at execution timeCalls a constructor to initialize the objectReturns a pointer of the type specified to the right of new Can be used to dynamically allocate any fundamental type (such as int or double) or any class typeHeapRegion of memory assigned to each program for storing objects created at execution time

  • Dynamic Memory Management with Operators new and deleteOperator deleteDestroys a dynamically allocated object Calls the destructor for the objectDeallocates (i.e., releases) memory from the heapThe memory can then be reused by the system to allocate other objectsNot releasing dynamically allocated memory when it is no longer needed can cause the system to run out of memory prematurely. This is sometimes called a memory leak.

  • Dynamic Memory Management with Operators new and deletenew operator can be used to allocate arrays dynamicallyDynamically allocate a 10-element integer array: int *gradesArray = new int[ 10 ];Size of a dynamically allocated arraySpecified using any integral expression that can be evaluated at execution time

  • Dynamic Memory Management with Operators new and deleteDelete a dynamically allocated array:delete [] gradesArray;If the pointer points to an array of objectsFirst calls the destructor for every object in the arrayThen deallocates the memory If the statement did not include the square brackets ([]) and gradesArray pointed to an array of objectsOnly the first object in the array would have a destructor call

  • static Class Membersstatic data memberOnly one copy of a variable shared by all objects of a classClass-wide information A property of the class shared by all instances, not a property of a specific object of the classDeclaration begins with keyword static

  • static Class Membersstatic member functionIs a service of the class, not of a specific object of the classstatic applied to an item at file scopeThat item becomes known only in that fileThe static members of the class need to be available from any client code that accesses the fileSo we cannot declare them static in the .cpp filewe declare them static only in the .h file.

  • static Class MembersUse static data members to save storage when a single copy of the data for all objects of a class will suffice.A classs static data members and static member functions exist and can be used even if no objects of that class have been instantiated.

  • Calling static member function using class name and binary scope resolution operatorDynamically creating Employees with newCalling a static member function through a pointer to an object of the class

    1// Fig. 10.23: fig10_23.cpp

    2// Driver to test class Employee.

    3#include

    4using std::cout;

    5using std::endl;

    6

    7#include "Employee.h" // Employee class definition

    8

    9int main()

    10{

    11 // use class name and binary scope resolution operator to

    12 // access static number function getCount

    13 cout

  • 29

    30 delete e1Ptr; // deallocate memory

    31 e1Ptr = 0; // disconnect pointer from free-store space

    32 delete e2Ptr; // deallocate memory

    33 e2Ptr = 0; // disconnect pointer from free-store space

    34

    35 // no objects exist, so call static member function getCount again

    36 // using the class name and the binary scope resolution operator

    37 cout

  • Fundamentals of Operator OverloadingTypes for operator overloadingBuilt in (int, char) or user-defined (classes)Can use existing operators with user-defined typesCannot create new operatorsOverloading operatorsCreate a function for the classOperator overloading contributes to C++s extensibilityone of the languages most appealing attributes

  • Overloading Stream Insertion and Stream Extraction Operators> operatorsAlready overloaded to process each built-in typeCan also process a user-defined classOverload using global, friend functionsExample programClass PhoneNumberHolds a telephone numberPrint out formatted number automatically(123) 456-7890

  • Overloading Unary OperatorsOverloading unary operatorsCan overload as non-static member function with no argumentsCan overload as global function with one argumentArgument must be class object or reference to class objectRemember, static functions only access static data

  • Overloading Unary OperatorsOverload ! to test for empty stringIf non-static member function, needs no argumentsclass String { public: bool operator!() const; };!s becomes s.operator!()If global function, needs one argumentbool operator!( const String & )s! becomes operator!(s)

  • Overloading Binary OperatorsOverloading binary operatorsNon-static member function, one argumentGlobal function, two argumentsOne argument must be class object or reference

  • Overloading Binary OperatorsOverloading +=If non-static member function, needs one argumentclass String { public: const String & operator+=( const String & ); };y += z becomes y.operator+=( z )If global function, needs two argumentsconst String &operator+=( String &, const String & );y += z becomes operator+=( y, z )

  • Most operators overloaded as member functions (except >, which must be global functions)Prototype for copy constructor!= operator simply returns opposite of == operator only need to define the == operator

    1// Fig. 11.6: Array.h

    2// Array class for storing arrays of integers.

    3#ifndef ARRAY_H

    4#define ARRAY_H

    5

    6#include

    7using std::ostream;

    8using std::istream;

    9

    10class Array

    11{

    12 friend ostream &operator( istream &, Array & );

    14public:

    15 Array( int = 10 ); // default constructor

    16 Array( const Array & ); // copy constructor

    17 ~Array(); // destructor

    18 int getSize() const; // return size

    19

    20 const Array &operator=( const Array & ); // assignment operator

    21 bool operator==( const Array & ) const; // equality operator

    22

    23 // inequality operator; returns opposite of == operator

    24 bool operator!=( const Array &right ) const

    25 {

    26 return ! ( *this == right ); // invokes Array::operator==

    27 } // end function operator!=

  • 1// Fig 11.7: Array.cpp

    2// Member-function definitions for class Array

    3#include

    4using std::cerr;

    5using std::cout;

    6using std::cin;

    7using std::endl;

    8

    9#include

    10using std::setw;

    11

    12#include // exit function prototype

    13using std::exit;

    14

    15#include "Array.h" // Array class definition

    16

    17// default constructor for class Array (default size 10)

    18Array::Array( int arraySize )

    19{

    20 size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize

    21 ptr = new int[ size ]; // create space for pointer-based array

    22

    23 for ( int i = 0; i < size; i++ )

    24 ptr[ i ] = 0; // set pointer-based array element

    25} // end Array default constructor

  • 100

    101// overloaded subscript operator for const Arrays

    102// const reference return creates an rvalue

    103int Array::operator[]( int subscript ) const

    104{

    105 // check for subscript out-of-range error

    106 if ( subscript < 0 || subscript >= size )

    107 {

    108 cerr a.ptr[ i ];

    122

    123 return input; // enables cin >> x >> y;

    124} // end function

  • 125

    126// overloaded output operator for class Array

    127ostream &operator

  • Retrieve number of elements in ArrayUse overloaded >> operator to input

    1// Fig. 11.8: fig11_08.cpp

    2// Array class test program.

    3#include

    4using std::cout;

    5using std::cin;

    6using std::endl;

    7

    8#include "Array.h"

    9

    10int main()

    11{

    12 Array integers1( 7 ); // seven-element Array

    13 Array integers2; // 10-element Array by default

    14

    15 // print integers1 size and contents

    16 cout

  • Use overloaded
  • Use overloaded == operator to test for equalityUse overloaded [] operator to access individual integers, with range-checking

    56

    57 if ( integers1 == integers2 )

    58 cout

  • Size of Array integers1 is 7

    Array after initialization:

    0 0 0 0

    0 0 0

    Size of Array integers2 is 10

    Array after initialization:

    0 0 0 0

    0 0 0 0

    0 0

    Enter 17 integers:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

    After input, the Arrays contain:

    integers1:

    1 2 3 4

    5 6 7

    integers2:

    8 9 10 11

    12 13 14 15

    16 17

    Evaluating: integers1 != integers2

    integers1 and integers2 are not equal

  • Size of Array integers3 is 7

    Array after initialization:

    1 2 3 4

    5 6 7

    Assigning integers2 to integers1:

    integers1:

    8 9 10 11

    12 13 14 15

    16 17

    integers2:

    8 9 10 11

    12 13 14 15

    16 17

    Evaluating: integers1 == integers2

    integers1 and integers2 are equal

    integers1[5] is 13

    Assigning 1000 to integers1[5]

    integers1:

    8 9 10 11

    12 1000 14 15

    16 17

    Attempt to assign 1000 to integers1[15]

    Error: Subscript 15 out of range