Download presentation
Presentation is loading. Please wait.
Published bySamson Norris Modified over 9 years ago
1
Concordia TAV 2002 Comp5421_411 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (1) Tianxiang Shen Summer 2002 Department of Computer Science Concordia University
2
Concordia TAV 2002 Comp5421_412 How to Use C++ Effectively C++ is a large and complex language. Its features are very beneficial when used correctly. Also some features of C++ are non intuitive, quite specialized, unnecessary, and unsuitable for general programming, these features are best avoided. It is important to have a set of guidelines on how to use C++ efficiently so that our C++ program reliable, readable, and maintainable.
3
Concordia TAV 2002 Comp5421_413 Declare Pointer Object C++ defines an object type called a pointer whose values are address of data in memory Syntax: pointer variable declaration ObjectType *objPtr; 1.objPtr is a C++ object whose value is the address of some ObjectType object in memory. 2.A pointer is declared like any other object. Two or more pointer objects can be declared in the same statement. The declaration can also include non-pointer objects. ObjectType objValue, *objPtr1, *objPtr2; yntax: Pointer
4
Concordia TAV 2002 Comp5421_414 Initializing pointer objType * objPtr;//uninitialized pointer Initialize the pointer 1. int intData=250, *intPtr; intPtr = &intData;//&intData: address of intData 2.int n = 33; int* pn = &n; 3. Int* px = 33;//Error
5
Concordia TAV 2002 Comp5421_415 Address-of Operator & In C++, we can obtain the address of a variable by using the address-of operator &, also called the reference operator Syntax: Form: &objName & is the unary operator Expression &objName evaluates the address of the variable objName Examples: 1.// declare a long object and a pointer to a long; long t = 50, *longPtr; // t at address 5000 longPtr = &t; // value of longPtr is 5000 2.// declare a short s with value 97 short s = 97;// s at address 5004 short *shortPtr = &s; // assign shortPtr value 5004
6
Concordia TAV 2002 Comp5421_416 Reference Type A reference, sometimes referred to as an alias, serves as an alternative name for an object. It is primarily used as formal parameter to a function. Syntax: T& refName =varName & is applied as a suffix to a type T, T& gives a derived type “reference to T” the reference is alias of the variable of type T refName is the name of the reference for the variable varName Example: 1.int s=5; int& rs=s;//rn is the synonym for n cout<<rs <<endl;//5 2.Int& rt = 44;// Error: 44 is not a variable 3.//Error: a reference must be referenced to an object int& rx;
7
Concordia TAV 2002 Comp5421_417 Dereference Operator * Dereference operator * is a unary operator If pn points to n, then the expression *pn evaluates to the value of n It is also called the indirection operator since it can indirectly access the value of an object from its pointer Example: 1.int n=44; int *pn = &n; cout<< *pn<<endl;//44
8
Concordia TAV 2002 Comp5421_418 Pointer Variable float * a; //uninitialized cout << "&a= "<< &a << endl;//&a= 006AFDF4 //a is a pointer to a float, it only allocates memory for itself cout << "a= "<< a << endl;//a= CCCCCCCC //The value of the pointer is some memory address, but the //memory at that address is not yet allocated cout << "*a = " << *a << endl;//*a = -1.#QNAN float f;//&pf = 006AFDEC float * pf = &f;//pb = 006AFDF0 //*pf = -1.07374e+008 float f = 3.4;//&pc = 006AFDE0 float *pf = &f;//pc= 006AFDE4 //*pc = 3.4
9
Concordia TAV 2002 Comp5421_419 Pointer to Pointer Int *pn=&n;// pn holds the address of n int ** ppn=&pn; // ppn holds the address of pn //i.e. ppn points to the pointer variable pn Example: int main(){ int n=44; cout << " n = " << n << endl; // n = 44 cout << " &n = " << &n << endl; // &n = 006AFDF4 int* pn=&n; cout << " pn = " << pn << endl;//? cout << " &pn = " << &pn << endl; //&pn = 006AFDF0 cout << " *pn = " << *pn << endl;//? int** ppn=&pn; cout << " ppn = " << ppn << endl;//? cout << " &ppn = " << &ppn << endl;// &ppn = 006AFDEC cout << " *ppn = " << *ppn << endl;//? cout << "**ppn = " << **ppn << endl;//? }
10
Concordia TAV 2002 Comp5421_4110 Referencing is the Opposite of Dereferencing Reference operator & and dereference operator * are inverses: n==*pn whever p==&n or *&n == n and &*pn = pn Example: 1. int n=7; cout<<(*&n==n)<<endl;// 1 cout<<*&n == n << endl;// Error Why? 2. int n= 7; int *pn = &n; cout<< (&*pn == pn) <<endl;// 1 cout<< &*pn==pn <<endl;// Error Why?
11
Concordia TAV 2002 Comp5421_4111 Lvalue (1) Originally, lvalue referred to things that appeared on the left side of assignments Lvalue that can appear left side of an assignment is called mutable lvalue, otherwise, it is called immutable lvalue 1.int n; n=44;//n is an lvalue n is called mutable lvalue Other examples: subscribed variable a[5] = 77; dereferenced pointer *p = 88; 2.(1) const int MAX=65535;//MAX is an lvalue MAX = 21034;//ERROR: MAX is constant MAX is called immutable lvalue (2) int a[2]={1,2}; int b[2]; b=a;//error C2106: '=' : left operand must be l-value
12
Concordia TAV 2002 Comp5421_4112 Lvalue(2) In general, an lvalue is anything whose address is accessible The declaration (type& refName = lvalue;) specifies an lvalue Examples: int& t = n;//OK int& r = 44;//ERROR: 44 is not an lvalue int& r = n++; //ERROR: n++ is not an lvalue int& r = cube(n); //ERROR: cube(n) is not an lvalue
13
Concordia TAV 2002 Comp5421_4113 Returning a Reference A function’s return type may be a reference, the value returned is an lvalue. Example: int main() { int m = 44, n = 22; cout << m << ", " << n << ", " << max(m,n) << endl; max(m,n) = 55; // changes the value of m from 44 to 55 cout << m << ", " << n << ", " << max(m,n) << endl; return 0; } int& max(int& m, int& n) // return type is reference to int { return (m > n ? m : n); // m and n are non-local references } Max() returns a reference to the larger of the two variables passed to it. Overloading Assignment Operator: className& operator=(const className&)
14
Concordia TAV 2002 Comp5421_4114 Array and Pointer Array name is the starting address of the array, it is a constant pointer Array subscript operator [] is equivalent to the dereference operator * Pointer arithmetic: Let T is the name of type, T a[10],*p;//both pointers to objects T p = a; //p points at a[0] cout<<*p; //*p=a[0] cout<<*(p+1); //*(p+1) = a[1] cout<<*(p+3); //*(p+3) = a[3] p += 2; cout<<*p; //*p = a[2] p++; cout<<*p; //*p = a[3] T *q; q =&a[5]; // *q = a[5] cout<<*(q+4); //*(q+4) =a[9] a = p;//Error Why?
15
Concordia TAV 2002 Comp5421_4115 Allocation Operator: new Syntax: The ‘new’ Operator Form:new objType; new objType(initvalue); Action: 1.The operator requests a block of memory from the heap. 2.The number of bytes is determined by sizeof(objType). 3.When an initial value is included, the operation assigns the value to the location on the heap. 4.If memory is not available, ‘new’ returns 0, the NULL pointer. Example: double *p = new double;// uninitialized double String *str = new String("HEAP");// string with value HEAP if (str == NULL) { cerr << "Memory allocation failure" << endl; exit(1); }
16
Concordia TAV 2002 Comp5421_4116 Allocation Operator: new (2) The following cases 1-4 are equivalent: 1. float * q; q = new float; *q = 3.14; 2.float * q = new float; *q = 3.14; 3.float * q = new float(3.14); 4.float * p = new float;//defensive if (p) *p = 3.14;
17
Concordia TAV 2002 Comp5421_4117 new Operator for Array Syntax: Form:new ObjType[n]; 1.The operator requests memory from the heap for n objects of type ObjType. 2.The locations in memory are uninitialized. Example: char *line = new char[80]; Dynamic array and static array: float* p =new float[20];//dynamic array //dynamic array is created at run time; its memory allocated only //when its declaration executes. float a[20];//static array //static is created at compile time; its memory remains allocated //through the run of the program
18
Concordia TAV 2002 Comp5421_4118 new Operator for Array (2) int main() { double* a; // a is simply an unallocated pointer int n; get(a,n); // now a is an array of n doubles delete [] a; // now a is simply an unallocated pointer again return 0; } void get(double*& a, int& n) { cout > n; a = new double[n]; for (int i = 0; i < n; i++) { cout << "i = "<< i << “ : address = " << a + i << " a[i] = "<< a[i] << endl;} } /* Enter number of items: 5 i = 0 : address = 007E0D30 a[i] = -6.27744e+066 i = 1 : address = 007E0D38 a[i] = -6.27744e+066 i = 2 : address = 007E0D40 a[i] = -6.27744e+066 i = 3 : address = 007E0D48 a[i] = -6.27744e+066 i = 4 : address = 007E0D50 a[i] = -6.27744e+066 */
19
Concordia TAV 2002 Comp5421_4119 new Operator for Class Object Syntax: ‘new’ Operator for Class Objects Form: new ClassName // use default constructor new ClassName(arguments) // pass arguments to constructor new ClassName [n] // default constructor used for each array element Action: 1. An argument list may be passed to the constructor when the ClassName object is allocated. 2. An array of ClassName objects can be declared only if the class has a declare constructor. Example: 1. KnightSquare * the_squares; the_squares = new KnightSquare[size*size]; the_squares[i] = new KnightSquareInfo; 2. KnightSolution sol = new KnightSolutionInfo(board_size); //KnightSolution i.e. class KnightSolutionInfo * 3. Vector *arr_vec = new Vector[8]; 4. Practice: defaultCon.cpp
20
Concordia TAV 2002 Comp5421_4120 Deallocation Operator: delete Deallocation operator: delete Syntax: The Delete Operators Form: delete objPtr;// deallocate dynamic storage delete [] objPtr;// deallocate dynamic array storage Action: Both operators take a pointer operand that was returned by a call to ‘new’. The corresponding memory that was allocated by new is deallocated by delete. For dynamic array storage, use delete [] operator so that the entire array is deallocated. Example: int *p, *q; p = new int(5); // allocate memory for a single integer with value 5 q = new int[20];// allocate memory for 20 long integers. array is uninitialized // deallocate the corresponding memory delete p;// deallocate a single int object delete [] q;// deallocate 20 int objects
21
Concordia TAV 2002 Comp5421_4121 Constant Pointer and Pointer to Constant 1.int n=44; int* p=&n;//pointer p ++(*p);// 45, ++p; // increments pointer p 2. int* const cp =&n;//constant pointer, ++(*cp)//ok, ++cp;// illegal, constant pointer 3. const int k=88; const int* pc = &k; // pointer to constant, ++(*pc);//illegal, int *pc is const ++pc; //ok 4. const int* const cpc=&k;//const pointer to a const, ++(*cpc);//illegal, int *cpc is const ++cpc; //illegal, pointer cpc is const
22
Concordia TAV 2002 Comp5421_4122 NULL char c=0; // ‘ \0 ’ null character, NUL, ASCII code is 0 char* pc =0; //initialize pc to NULL, //NULL pointer cannot be dereferenced. *pc =22 // fatal error a reasonable precaution is to test a pointer before dereference it: if (pc) *pc =22;// i.e. (pc!=NULL)
23
Concordia TAV 2002 Comp5421_4123 Review Exercise Assume: int x=42, *px=&x, y=*px, **ppx=&px; bool c=true, *pc=&c; What will be the value of each of the following expression? 1) y,2)c+1,3)pc+1,4)px+1, 5)*px+1,6)*(px+1),7)*ppx,8)**ppx Assume: the address of x is 3700, the address of c is 3704, and the address of px is 3712
24
Concordia TAV 2002 Comp5421_4124 Answer Assume: int x=42, *px=&x, y=*px, **ppx=&px; bool c=true, *pc=&c; What will be the value of each of the following expression? 1) y,2)c+1,3)pc+1,4)px+1, 5)*px+1,6)*(px+1),7)*ppx,8)**ppx Assume: the address of x is 3700, the address of c is 3704, and the address of px is 3712 Answer: 1)42,2)2,3)3705,4)3704, 5)43,6)??,7)3700,8)42
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.