2. SE___Lecture_02___OOP_in_C___.ppt
-
Upload
antonio-kumar -
Category
Documents
-
view
113 -
download
2
Transcript of 2. SE___Lecture_02___OOP_in_C___.ppt
Object-Oriented Programming in C++ CS20006: Software EngineeringLecture 02Prof. Partha Pratim Das
Jan 2013
Object-Oriented Modeling & Programming
PROGRAMMING IN C++Jan 2013 OOP in C++ 2
Topics Procedural Enhancements in C++ over C Classes Overloading Inheritance Type Casting Exceptions TemplatesJan 2013 OOP in C++ 3
Object Oriented Programming in C++
PROCEDURAL ENHANCEMENTS IN C++Jan 2013 OOP in C++ 4
TOPICS Const-ness Reference Data Type Inline Functions Default Function Parameters Function Overloading & Resolution Dynamic Memory Allocation
Jan 2013
OOP in C++
5
const Quantifier const qualifier transforms an object into a constant. Example: const int capacity = 512; Any attempt to write a const object is an error Const object must be initialized.
Pointer to a non-constant object can not point to a const object;const double d = 5.6; double *p = &d; //error
Pointer to a constant object vs. constant pointer to an object.const double * pConstantObject; double * const *pConstantPointer;Jan 2013 OOP in C++ 6
References A reference is an additional name / alias / synonym for an existing variable Declaration of a Reference & = ;
Examples of Declarationint j = 5; int& i = j;
Jan 2013
OOP in C++
7
References Wrong declarations int& i; // must be initialized int& j = 5; // may be declared as const reference int& i = j+k; // may be declared as a const reference
Often used as function parameters : called function can change actual argument faster than call-by-value for large objects
Jan 2013
OOP in C++
8
References Do not .. Cannot have an array of references No operator other than initialization are valid on a reference. Cannot change the referent of the reference (Reference can not be assigned) Cannot take the address of the reference Cannot compare two references Cannot do arithmetic on references Cannot point to a reference
All operations on a reference actually work on the referent.Jan 2013 OOP in C++ 9
Returning a ReferenceReturning a reference return value is not copied back may be faster than returning a value calling function can change returned object cannot be used with local variables
Jan 2013
OOP in C++
10
Returning a Reference#include int& max(int& i, int& j) { if (i > j) return i; else return j; } int main(int, char *[]) { int x = 42, y = 7500, z; z = max(x, y) ; // z is now 7500 max(x, y) = 1 ; // y is now 1 cout