OOP in C++

194
Object-Oriented Programming in C++ Jan-Feb 2014 Lecture 02-

description

This is an overview of C++ (based on 1999 / 2003 standard) and its use in Object Oriented Programming. The presentation assumes that the audience knows C programming.

Transcript of OOP in C++

  • 1. Object-Oriented Programming in C++ Jan-Feb 2014 Lecture 02-

2. PROGRAMMING IN C++ Object-Oriented Modeling & Programming OOP in C++ 2Jan 2014 3. Topics Procedural Enhancements in C++ over C Classes Overloading Inheritance Type Casting Exceptions Templates 3OOP in C++Jan 2014 4. PROCEDURAL ENHANCEMENTS IN C++ Object Oriented Programming in C++ Jan 2014 4OOP in C++ 5. TOPICS Const-ness Reference Data Type Inline Functions Default Function Parameters Function Overloading & Resolution Dynamic Memory Allocation 5OOP in C++Jan 2014 6. 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; 6OOP in C++Jan 2014 7. References A reference is an additional name / alias / synonym for an existing variable Declaration of a Reference & = ; Examples of Declaration int j = 5; int& i = j; 7OOP in C++Jan 2014 8. 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 8OOP in C++Jan 2014 9. 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. 9OOP in C++Jan 2014 10. Returning a Reference Returning 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 10OOP in C++Jan 2014 11. Returning a Reference #include using namespace std; 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