You are on page 1of 233

Object Oriented Programming

Uttam K. Roy
Dept. of IT, JU u_roy@it.jusl.ac.in

Books
‡

B. Stroustrup, ³The C++ Programming Language´, Addison Wesley publication E. Balagurusamy, ³Object Oriented Programming with C++´, Tata McGrawHill publication Yashwant Kanetkar, ³Let Us C++´, BPB publication Lipman, ³C++ Primer´

‡

‡

‡

©U.K.R., 2008

OOP

2

What Is C++?
Compatible extension of C Support Object Oriented Programming Support for Data Abstraction

©U.K.R., 2008

OOP

3

Background
C++ designed by Bjarne Stroustrup (AT&T Bell Labs) Originally only meant as a pre-processor to improve on some of the inadequacies of C First commercial release 1985 Even today many consider C++ is not an object oriented language but rather an object oriented compiler-linker (subtle difference we'll learn about later).
©U.K.R., 2008 OOP 4

R.BPCL C Algol68 Algol68 Simula67 Simula67 (Smalltalk) (Ada) (LISP) ©U.K.. 2008 OOP 5 C++ .

.R. 2008 .Strengths and Weakness of C Strengths     Flexible (you can make mistakes in a wide variety of ways!) Efficient (you can make those mistakes very quickly!) Available (everyone can make mistakes together!) Portable (you can transport those mistakes to other systems!) Very untidy syntax Lack of type safety memory management not automatic OOP 6 Weaknesses    ©U.K.

R. 2008 OOP 7 .K.Philosophy of C++ Keep the strengths and repair the weaknesses       Efficiency is maintained Compatibility is maintained with C Operate in all environments C can Improved typing Abstraction and Data encapsulation vastly improved Inheritance and Polymorphism introduced ©U..

.©U.K. 2008 OOP 8 .R.

. namely:      Definition of class and declaration of objects Enforcement of information hiding The ability to define an inheritance hierarchy of classes The ability to code polymorphic methods Invocation of an object¶s method by message passing OOP 9 ©U.OOP Language? An Object Oriented Programming Language is one which fully supports the fundamental concepts of Object Oriented approach. 2008 .K.R.

2008 OOP 10 . Paradox.Examples of OOP Language Pure Object Oriented Programming Languages   SmallTalk (The first OOPL) Eiffel (powerful language that supports selective inheritance) C++ (does not enforce information hiding) Object Pascal (does not support information hiding and does not support multiple inheritance) Object COBOL (does not enforce information hiding) Visual Basic.K. ToolBook etc.R. Languages with OO Extensions    Languages with OO ³look and feel´  ©U..

.Differences between C and C++ OO programming constructions Function prototyping Default parameter values Reference parameters Enumeration names Use of const Inline functions Block declarations Different syntax for cast operator Function and operator overloading New syntax for comments Operators for I/O streams New libraries ©U.K.R. 2008 OOP 11 .

K.R. 2008 OOP 12 ..Key Words for C and C++ C and C++ Key Words auto break case default do double float for goto register return short struct switch typedef volatile while Additional C++ Key Words asm catch class new operator private this throw try char else if signed union const enum int sizeof unsigned continue extern long static void delete friend protected public virtual inline template ©U.

Non-Object Oriented Extension from C to C++ .

} } ©U. cout << c << ³ ³ << f << ³\n´.Flexible declaration In C. 2008 OOP 14 . when you write a function.0.R. all the declaration of local variables must appear at the top of the function or at the beginning of a block #include <iostream.. f < 100.K.h> main( ) { for(int f = 0. f++) { float c = (f ± 32)*5/9.

structs. 2008 OOP struct A { int x. classes. so you can say: ©U.R. typedef struct A A. a common style of variable declaration is struct A { int x. 15 . unions. }. E e. In C++. and enum names are automatically type names. }. A a. A a.Type Names In C..K. enum E {ee}.

whereas in c they can not //C style enum Color {Red. //C++ style enum Color {Red=2.R. Blue=6}. Armstrong one=first. Blue}. Green. third=371}. Color background=Blue.K.Enumeration names In C++.. Green=4. ©U. 2008 OOP 16 . second=370. Armstrong two=second. enum Armstrong {first=153. enumeration names can have values assigned to them.

//C style float g = (float)i/2.R. j. type casting can be done in two different ways:   C style cast Function notation cast int i.K. //function notation float h = float(j)/2 ©U.. 2008 OOP 17 .Type Casting In C++.

K. functions may have a prototype defined before implementation.R. void setBackground(Color c=Red). 2008 OOP 18 . ©U. In C++ it is compulsory In addition..Function prototype and default values In C. arguments may have default values specified in the prototype which can be used when function is called without any argument int square(float).

cout << x. int main() { int x=5.Accessing variables Global variable can be accessed using scope resolution operator while a local variable with the same name is already declared int x=2. 2008 OOP 19 . //local x cout << ::x.R. //global x } ©U.K..

2. PI=6. float area = PI*radius*radius. 2008 .0.Constant variable Value once set can never be changed Example: main( ) { const float PI = 22/7. int radius = 10.K.. //error } Benefits:   Impossibility of accidental modification of data Increases readability OOP 20 ©U.R.

y = 4-2*4-2 = -6 Using const const int x = 4-2.Const and #define Incorrect Result:  Using #define #define x 4-2 main( ) { int y = x*x. main( ) { int y = x*x.R. 2008 //correct. y = 2*2 = 4 OOP 21 . } ©U..K. }  //incorrect.

K. cout << v*v.R. cin >> n. cout << v*v. } else { #define v -n. 2008 OOP 22 . cin >> n. if( n > 0) { const int v = n.Const and #define Impossibility of creating variable conditionally main( ) { int n.. if(n > 0) { #define v n./*do rest thing«*/ } else { const int v = -n./*do other thing«*/ } } ©U. } } main( ) { int n.

K. 2008 OOP 23 . //pointer r is const.R. //error p = &y. //error s = &y. //variable pointed by p. but variable pointed by r. //error ©U. //same as p int * const r = &x. //error const int * const s = &x.. const int *p = &x. but pointer p is not *p = 8. //ok r = &y. is const.Constants and Pointers int x = 4. is not *r = 10.y = 6. //ok int const *q = &x. //pointer as well as variable pointed by s are const *s = 12.

//error src[0] = µa¶.Application void Strcpy(char * const dst. //error dst = &ch. //error } ©U.K. 2008 OOP 24 .. const char * const src) { char ch.R. src = &ch.

K. etc.. 2008 OOP 25 .Reference Variable ‡ Creates an alternate name or alias for the variable ‡ Can be used to read or modify the original data stored in that variable ‡ Syntax of reference variable declaration: Standard or user defined data type: char. Reference operator C++ alias variable C++ original variable DataType & ReferenceVariable = OriginalVariable OrigialVariable ReferenceVariable ©U. int.R. short. float.

all the operation will be implied on original variable ‡ Can be viewed as a const pointer without dereferencing notation ‡ i. e.. // increment count normally ++ref. ref = &y. //error 26 . 2008 OOP int x = 2.y = 6. // declare integer variable count int &ref = count.Reference Variable int count = 1. // increment count (using its alias) 1000 count 3 2 1 ref ‡ Properties of a reference variable ‡ Cannot exists independently²must be initialized when they are created ‡ Cannot be manipulated independently²except initialization operation. // create ref as an alias for count count ++.K. ©U. int * const ref = &x. object/variable to which a reference refers cannot be changed. //ok. x=4 *ref = 4.R.

R..Restrictions You cannot reference of a reference variable You cannot create array of references You can not create pointer to a reference ©U.K. 2008 OOP 27 .

//read only alias for x p = 8. y = 12. y is const and r is a read only alias //error //error OOP 28 .R. //error x = 8. const int &p = x. //ok const int y = 6. r = 10.K. int & q = y. ©U.Constants and References Example: int x = 4.. const int &r = y. 2008 //declaration syntax error //ok.

temp = a. b = temp..b formal params a 5 4 temp b 4 5 4 OOP 29 .Usage of References ‡ Call by value: main( ) { int x=4. 2008 //a. int b) { int temp. //actual args change(x. } x 4 y 5 void change(int a. a = b. y).R.K. y=5. } ©U.

*b = temp. int *b) { int temp. temp = *a.. y=5. 2008 OOP b 1006 1002 1004 1000 1008 temp 4 30 .K. } ©U. //actual args change(&x. *a = *b. } 1000 x 5 4 1002 y 4 5 a void change(int *a.R. &y).Usage of References ‡ Call by address: main( ) { int x=4.

Usage of References ‡ Call by reference: main( ) { int x=4. a = b.. } ©U. y).K. //actual args change(x.b formal args temp 4 OOP 31 . 2008 //a. temp = a. } x 5 4 a y 4 5 b void change(int &a.R. b = temp. int &b) { int temp. y=5.

int *arr.. So passed argument may be changed unknowingly. int &max. bool &found. //take three integers and return sum. //find an element µele¶ in array µarr¶ and if found return location ©U. max and min void find(int ele.K.R. int &min). float deteminant(const Matrix &m) { /*find determinant of matrix m here*/ } ‡ Possible solution²use const ‡ Possibility to write generic function ‡ more that an one value can be retrieved from a a function int f(int a. int c. int b.Usage of References ‡ Avoid unnecessary copying float deteminant(Matrix &m) { /*find determinant of matrix m here*/ } ‡ Danger with references ‡ Function invocation does not indicate that references are used. 2008 OOP 32 . int &location).

int &f() { return x. Result x=4 ©U..R.K. 2008 OOP 33 . } int a = 4.Return by References int x = 2. Function call f() = a.

Inline Functions ‡ Eliminates the function-call overhead (caused by jumping in and out of functions having few statements) involved in the conventional functioning approach. 2008 OOP 34 .K..R. often-used functions ©U. ± Keyword inline before function ± Asks the compiler to copy code into program instead of making function call ± Compiler can ignore inline ± Good for small.

K. Keyword.Inline Functions Syntax of inline function definition: ‡ Specified using the same syntax as any other function except that they include the inline keyword in the function declaration.. function qualifier inline ReturnType FunctionName(Parameters) { // Body of a main function } ©U. 2008 OOP 35 .R.

//« } OOP //impossible to substitute 36 . 2008 void main( ) { //« a = 120. cin >> n. //« } void main( ) { //« a = 5*5. b = fact(4).Inline Functions Example inline int sqr(int num) { return num * num. b = n*n. } void main( ) { compiler //« a = fact(5). } void main( ) { compiler //« a = sqr(5). b = sqr(n).R.. c = fact(n). //« } ©U. cin >> n. c = fact(n).K. //« } inline int fact(int n { return (n < 2?1:n*fact(n-1)). b = 4*fact(3).

. E.g.R. 2008 OOP 37 .K..Inline Functions versus Macros Inline functions: parsed by the compiler Macros : expanded by the preprocessor.y) ((x>y)?x: y) Limitation with macro: Macros are not functions and errors are not checked at compilation time until it is used. ©U. #define max(x.

©U. In some cases.2).2).R..} void main() { cout << div(5.5 } ‡ Expressions passed as arguments to inline functions are evaluated once.y) (x/y) void main() { cout << div(5.K. //wrong result 2 } inline float div(float a. #define div(x. 2008 OOP 38 . expressions passed as arguments to macros are evaluated more than once. float b) { return a/b .Inline Functions versus Macros Reasons why Inline functions are better than macros: ‡ Follow all the protocols of type safety enforced on normal functions. //correct result 2.

q=3. cout<<³r = ³ << r << ³s = ³<<s.R.s.. r=SQUARE(++p). inline function square( )  var µq¶ is incremented only once and is assigned to j then j * j is returned.K. 2008 . } void main( ) { int p=3.r.Inline Functions versus Macros # define SQUARE(num) num * num Output inline float square(float j) { return (j * j). s=square(++q). OOP 39 ©U. } r =25 s =16 Macro SQUARE( ) is expanded as r = ++p * ++p  In macro expansion p is incremented twice.

float abs(float). void print(int). void print(Student). void print(Matrix m). 2008 OOP 40 . void print(int *. void print(float). //print an integer //print a float //print an array //print a matrix //print student data ©U.K. type and order of arguments ‡ It is a kind of Compile time Polymorphism int abs(int).Function Overloading ‡ Having more than one function with the same name differing in number. double abs(double).R.. int).

float) The compiler will not be able to identify the function to be called sum(1. int(1. 2.1).g.Function Overloading Issues in Function Overloading ‡ Functions differing in their return types only cannot be overloaded. 2008 //ambiguity:which sum? sum(int(1. float to double etc.1)) or sum(float(1.R.2).int) and sum(float. char is converted to int.1). ©U.. If no accurate match found may lead to ambiguity as internal type Ambiguity ‡ ‡ conversions may take place. float(2.K..2)? OOP 41 . char pop(Stack &). e. Consider: sum(int. ± compiler tries out implicit conversions. int pop(Stack &). If no accurate match found.1. Overloaded function resolution ‡ ‡ The compiler attempts to find an accurate function definition that matches in types and number of arguments and invokes the function. float pop(Stack &).

0. or function calls ©U.R. drawCircle(0.100. when their values are neglected or insufficient number of values are furnished during function calls. ‡ Can be constants.100).0.100). GREEN). drawCircle(0. GREEN). int color=WHITE).100. 3 arguments needed void drawCircle(int x. global variables.K. drawCircle(0.Default Values void drawCircle(int x. 2008 OOP 42 .0.0.. int radius. int y. drawCircle(0. //draw with WHITE color //error. int radius). //color=WHITE //color=GREEN ‡ Function arguments assume default values. int y.

R. //x = 3. 2008 OOP 43 .Default Values int myFunction(int x = 1. 5..int z = 3) myFunction(3). 5). y = 5 and z = 7 ©U. 7).K.int y = 2. y = 5 and z gets default myFunction(3. y and z get defaults (rightmost) myFunction(3. //x = 3. //x = 3.

Default Values
Basic rules: ‡ When a default is provided, all parameters must be given defaults.

remaining

‡ Default values must be of the correct type. ‡ Defaults can be placed on the function prototype or the function definition.

©U.K.R., 2008

OOP

44

Object Oriented Programming 
Program is composed of a collection of individual units, or objects, as opposed to a traditional view in which a program is a list of instructions to the computer
Object B

Data variable
Object A Object C

Member Function Data variable Member Function
©U.K.R., 2008 OOP

Data variable Member Function
45

Object Oriented programming?
‡ In an object ±oriented environment, software is a collection of discrete objects that encapsulate their data as well as the functionality to model real-world objects. Objects: ‡ Packaging data and functionality together into units within a running computer program; ‡ The basis of modularity and structure in an object-oriented computer program. ‡ Self contained and should be easily identifiable.

©U.K.R., 2008

OOP

46

Benefits of Object Orientation
‡ Modularity: Since the whole system is being modeled as classes and various methods are divided according to the respective functionalities in respective classes, modularity increases. ‡ Deferred Commitment: ‡ Since classes can be modified without modifying the actual code where the classes are being used, flexibility towards the commitment increases (Easier maintenance). ‡ The internal workings of an object can be redefined(easily) without changing other parts of the system. ‡ Reusability: Since defining classes through inheritance helps in reusability thus faster production.

©U.K.R., 2008

OOP

47

2008 OOP 48 .K.Benefits of Object Orientation ‡ Higher Quality: Since deriving classes from existing classes which are working successfully. ©U.R.. ‡ Reduced cost: Because of reusability ‡ Increased Scalability: Easier to develop (integrate)large systems from well tested smaller systems.

e. ‡ Create objects of various classes.. collection of objects with common characteristics.Classes and Objects ‡ Logical Abstraction ‡ A Class is a description of common properties of objects that belong to the class i. are the data and functions replicated? ©U. 2008 OOP 49 .. ‡ For individual objects.K.R. These are the physical existence.

‡ Association .A software module that provides both procedural and data abstraction.R. It describes a set of similar objects. 2008 OOP 50 .A relationship between two classes that represents the existence of a set of links between objects of the two classes window origin size open() close() move() display() Window Class ©U.K..A simple data item present in all the instances of a class ‡ Data type . called its instances ‡ Attribute .Terminology ‡ Class .A name or label for a set of values and some operations which one can perform on that set of values.

. 2008 OOP 51 .Classes Polygon Abstract into vertices border area fillColor draw( ) erase( ) move( ) Class Attributes Polygon Objects Operations ©U.K.R.

2008 OOP Atrributes and their class 52 .K..Classes Attributes Customer name address phone birthDate attributes Wall height::Float width::Float Thickness::Float isMovable::Boolean=false attributes Customer Atrributes Atrributes and their class Student roll::Integer name::String address::String birthDate::Date attributes PC hdd::Component ram::Memory Mouse::InputDevice keyboard::OutputDevice attributes Atrributes and their class ©U.R.

Classes Operations Rectangle area() grow() move isEmpty() Operations TeperatureSensor operations reset() setAlarm(t: Temperature) Value(): Temperature Operations operations Register endSale() enterItem(id: ItemId.K.. pin: Integer) withdraw(amount: Float) deposit(amount: Float) balance(): Float Oerations ©U. qty: Integer) pay(cashTendered: Money) Operations ATM validate(crd: ATMCard. 2008 OOP 53 .R.

2008 OOP 54 . only the object's own internal methods are (generally) allowed to access its state..Encapsulation ‡ Bundling of the data and methods together Transaction ‡ Ensuring that users of an object cannot change the internal state of the object in unexpected ways. +execute() +rollback() #priority() -timestamp() ©U. ‡ Each object exposes an interface that specifies how other objects may interact with it.R.K. Other objects will rely exclusively on the object's external interface to interact with it.

Inheritance ‡ Ability to extend/subclass the behavior of existing class without changing the original class ‡ New class is called derived class/sub class ‡ Old class is called super class/base class ‡ Sub class inherits all the behavior of its super class ‡ New fields and methods can be added in the sub class ©U. 2008 OOP 55 .K..R.

Inheritance Shape origin move() resize() display() base/parent class Party generalization Rectangle tl: Point rb: Point area(): Float « Circle radius: Float center: Point area(): Float « Polygon points:List area(): Float display() « Customer Supplier Employer Square leaf class ©U..K.R. 2008 derived/child class OOP 56 .

R.Polymorphism ‡ Many(poly-) forms(-morph) ‡ Function overloading ‡ Operator overloading ‡ Inheritance ‡ Virtual function ©U. 2008 OOP 57 .K..

p2. p1. p1. y.K.R. } x 2 y 4 x 6 p2 y 8 Objects Initialization of member variables ©U.x=2.Classes & Objects p1 struct Point { int x.x=6.. 2008 OOP 58 . void main( ) { Point p1.y=4. /*«*/ }.y=8. float distance(Point). p2. float d = p1. p2.distance(p2).

6 8.img=3.R. c1.img=8.real=5. c2.Classes & Objects c1 struct Complex { double real.5 3. c2.8 Objects Initialization of member variables ©U.add(c2).. 2008 OOP 59 . c1. img.K.6. /*«*/ }.4 c2 real img 5. } real img 1. Complex add(Complex).4. void main( ) { Complex c1. c2. Complex c3 = c1.real=1.8.5.

2008 OOP 60 .Access Control ‡ A member of a class can be private.. protected. public. its name can be used by any function. its name can be used only by member functions and friends of the class in which it is declared and by member functions and friends of classes derived from this class. we use another access specify namely protected. ‡ If a member of a class is private. or public. ‡ If it is protected. a member of a class can be private. its name can be used only by member functions and friends of the class in which it is declared.R.K. ©U. So. (In inheritance.) ‡ If it is public.

//not accessible from outside //ok.8). temp. 2008 OOP 61 //error.Access Control struct Complex { private : double real. double i) { real = r. double d = c1. public : void set(double r. c1. //real and img are //accessible from member function } /*«*/ }. 8.4.img=3.set(5. } ©U.6. c1. c2. void main( ) { Complex c1. real and img are private.K.R.img). c1.5.4).add(c2).real. img+c. 3.real=1.5. img. c2.set(real+c.set(1. access through public member function //ok. access through public member function . } Complex add(Complex c) { Complex temp. img = i..

but it can be defined as inline using the inline keyword. void sety(int yy) {y=yy.x)+(y-p.x)*(x-p.} float distance(Point).. /*«*/ }.Inline Member Functions ‡ If a member function is implemented outside the class braces.} inline float Point::distance(Point p) { return sqrt((x-p. y.y). 2008 OOP Member function prototype declaration Member function defined inside²inlined by default Member function defined outside²not inlined Member function defined outside² inlined explicitly 62 . it is not inlined by default. void Point::setx(int xx) {x=xx. } ©U.y)*(y-p. void setx(int).K.R. class Point { public: int x.

} setx(2. setx(6. &p1). p1.this pointer class Point { public: int x. Point *this) { this->x = xx. y p1 x.. } 63 . y. y p2 void setx(int xx) { x = xx. void setx(int xx) {x=xx.setx(6). ©U. 2008 OOP void setx(int x) { this->x = x.} /*«*/ }. } x. void main( ) { Point p1. p2. } void setx(int xx.R. p2.K.setx(2). &p2).

distance(p2). /*«*/ }.K.setx(6).. p2.sety(8). p2. float d = p1.Constructors and Destructors class Point { private: int x.sety(4). 2008 OOP Initialization of member variables 64 . y. public: void setx(int x) {this->x=x.} void sety(int yy) {y=yy.} float distance(Point). p1.setx(2). p2. void main( ) { Point p1. p1.R. } ©U.

}. // if not initialized garbage } void main( ) { Point p.y.x<<"y= "<<p. x=2. Constructor declared Constructor defined Object created and initialized by constructor Inside Point( ) Inside main( ) x= 2 y= 4 Point( ). y. cout<<"x= " << p. //Point p = Point(). Point::Point(void) { cout<<" Inside Point( )\n".Solution is constructor class Point { public: int x. } ©U.y=4..R. 2008 OOP Object p x= 2 y= 4 65 .K. cout<<"Inside main( )\n".

R. ‡ Constructors do not return values. ‡ A constructor on each object is called when it is created ‡ They are commonly used to initialize the member variables.. They have no return type specified ©U.Constructors contd.. ‡ Constructors are special member functions with the same name as the class.K. 2008 OOP 66 .

R.Constructors contd. 2008 OOP 67 ..K. ‡ The purpose of a copy constructor is to initialize a new object of a given class by copying an existing object of that class. A constructor is called whenever an object is defined or dynamically allocated using the ³new´ operator ‡ If no constructor is explicitly written then a default is created (not in the case of const and reference data members).. ‡ ©U.

delete(f). x = new int[100]. str[0] = µC¶. delete(str). class Point { int x. 2008 OOP 68 . float *f.K. ptr[i] = &p.R. } delete(x). y. f = new float[10]. ©U. str[3] = µ\0¶.. for(int i=0.Dynamic Memory Allocation int *x. char *str. Point *ptr. str = new char[4]. ptr = new Point[5]. }.i<5. str[1] = µ+¶. str[2] = µ+¶. delete(ptr).i++) { Point p.

20). Point p3 = p2. int j). 2008 OOP Parameterized Constructor Constructor called implicitly Object p1 Object p2 x= 10 y= 20 x= 30 y= 40 69 . y. Point(int i.y=j.R.Constructors with arguments ‡ Parameters can be passed to the constructors class Point { public: int x.K. } void main( ) { Point p1(10. }. Point::Point(int i. 40).. } ©U. int j) { x=i. Point p2 = Point(30.

y. No arguments: Point p.Multiple constructors declared in a class ‡ All constructors have different number of arguments ‡ Depending on the number of arguments.4) Copy constructor: Point p2=p1 70 Point(const Point & i) {x=i.. int j) {x=i.}.y=20. Point(int i.R. 2008 OOP .Overloading Constructors ‡ Overloading Constructors . compiler executes corresponding constructor Point( ) {x=10.y=j.y=i.}.K.}. ©U.x. Two arguments: Point p1(2.

int j=10) { x=i. } }.. Point p2(8. 2008 OOP 71 .y=j.R.K.Constructors with default arguments ‡ Constructors can be defined with default arguments class Point { public: int x. 9). y. } Object p1 Object p2 x= 1 y= 10 x= 8 y= 9 Default value for j=10 (Used by the object p1) ©U. Point(int i. void main() { Point p1(1).

//Copy constructor Point p3=p1. //Object created and initialized Point p2(p1). Point p1(10). //Member wise copy ©U. 2008 OOP 72 . ‡ If there is no copy constructor defined for the class. C++ uses the default copy constructor which copies each field. p4=p1. makes a shallow copy. ie. //Copy constructor Point p4..Copy Constructors ‡ Constructors can accept arguments of any data type including user defined data types and an object of its own class ‡ C++ calls a copy constructor to make a copy of an object.R.K.

2008 . o4=o1.K.} aClass(aClass &j) {x=j.. aClass o4.. class aClass { public: int x. aClass o2(o1). aClass(){ } aClass(int i) {x=i.} }. aClass o3=o1.Copy Constructors contd. void main() { aClass o1(10).x. } Objects o1 x=10 o2 x=10 OOP o3 x=10 o4 x=10 73 ©U.R.

size s1 a 3 6 9 4 Stack s1(4). } int pop() { return a[top--].R. public : Stack(int sz):top(-1) { top = -1.a[i]. size..i++) a[i]=s. s2=s1. a = new int[size=sz]. } }.size]. delete(temp) } }.Importance of Copy Constructors class Stack { private : int *a.i<size. top. 2008 OOP top size a After s2=s1 74 top . Solution class Stack { public : Stack(const Stack &s) { top=s.K. a=new int[size=s.top. for(int i=0. } void push(int item) { a[++top]=item. s2 ©U. int *temp=a.

Solution class String { « String(const String &str) { length = str. s2=s1. str. 2008 OOP .K.. } }. char *buf. public: String(int size) { buf = new char[(length = size)+1].length.R. } }.buf). buf = new char[length+1]. s1 buf length buf s2 length C + + 4 3 6 9 \0 After s2=s1 75 ©U. strcpy(buf.Importance of Copy Constructors class String { int length. String s1(4).

Destructors ‡ When an object goes out of scope then it is automatically destructed..R.K. ‡ It performs clean up of the object ( using µdelete¶ in the case of allocating memory inside the object using µnew¶ ) ‡ Destructors have no arguments and thus cannot be overloaded ©U. 2008 OOP 76 .

R..Destructors contd.K.. Declaration ± Same name as class ‡ Preceded with tilde (~) ~Point( ) { } ©U. 2008 OOP 77 .

. 2008 OOP 78 . p2. y.Static Members class Point { int x. y p1 x. y p2 ‡ For each object.R. an instance of each non-static data member is created ©U. /*«*/ }. x.K. Point p1.

K.Static Members ‡ Static Data Members: Static members are members that are single shared member common to all the objects created for a particular class. 2008 OOP 79 .R. Object A Object B Static variable Object C ©U.. Memory allocation is done only once and not every time an object is created.

‡ Only one copy of static data member will exist irrespective of the number of objects created ‡ Static functions can access only static variables ‡ Efficient when single copy of data is enough ‡ May seem like global variables.Static Members contd.. 2008 OOP 80 . but have class scope ‡ Only accessible to objects of same class ©U.R.K.

R. 2008 currentBal=0 OOP currentBal=1 81 . Shared by all objects Object yourAccount Object myAccount ©U. int SavingsAccount::RateofInt=10.K. yourAccount(1)... SavingsAccount myAccount(0).Static Members contd. public : static int RateofInt. ‡ Static Member Example class SavingsAccount { private: int currentBal.} }. SavingsAccount(int b) {currentBal=b.

R. int Car::nextSerial=10.. Shared by all objects Object anotherCar Object aCar ©U. anotherCar. Car():serialNo(nextSerial++) {} }. public : static int nextSerial. Car aCar. ‡ Static Member Example class Car { private: const int serialNo.Static Members contd.K. 2008 serialNo=10 OOP serialNo=11 82 ..

2008 OOP 83 .K. ©U.Static Member function ‡ Static Member function example class Car { « public : static int nextSerial. } }.R.. static void reset() { nextSerial = 0.

‡ Static Data Members: class SavingsAccount Only one copy should { be available as all private: objects should have char name[30].R. } } ©U. 2008 OOP 84 . public: To make CurrentTate accessible to all objects SavingsAccount().K. same Interest rate float total.. void EarnInterest() { Declare CurrentRate as total + = CurrentRate * total. float CurrentRate.. static float CurrentRate.Static Members contd.

K.y.R. public : void setx(int xx) {x=xx. ©U. Any attempt to modify the member variables is an error 85 .} int getx( ) const {return x. ‡ If a const function attempt to change the data..Constant Functions ‡ Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. the compiler will generate an error message. ‡ Illegal to declare a const member function that modifies a data member class Point { int x. 2008 OOP const(read only) member function..} }.

Constant Functions ‡ const member functions can be invoked on const as well as non-const objects but non-const member functions can be invoked on non-const objects only class Point { int x. //OK cp. //OK p.R.setx(2).} }. Point p. int x = cp. //OK ©U. public : void setx(int xx) {x=xx.. //Error x = p..y.} int getx( ) const {return x.setx(2).getx().getx(). 2008 OOP 86 . const Point cp.K.

K. 2008 OOP 87 ..Mutable data members class Point { mutable int x.R. public : void setx(int xx) {x=xx. ©U. //OK } }.} int getx( ) const { x++.

Mutable data members class Point { mutable int cnt. ©U.R.. count().K... 2008 OOP 88 . } int count( ) const { return cnt++. //OK } }. public : void setx(int xx) { .

K. even though those variables should not be made public ‡ Friend can be ± A non-member function ± A member function of a class ± An entire class ©U.Friend Functions and Classes ‡ A friend of a class can access even its private members. 2008 OOP 89 .R.. ‡ Useful when one class wants to see the private member variables of another class.

Non-member as a friend example void f() { /*«*/ } class X { friend void f(). }. ‡ A non-member function can be a friend of any number of classes ©U.R. 2008 OOP 90 ..K.

class Humidity { public: friend void PrintWeather(Temperature &t. }.R. Humidity &h) { //print both temperature and humidity } ©U. void PrintWeather(Temperature &t. }. 2008 OOP 91 ..K.Non-member as a friend example class Humidity. class Temperature { public: friend void PrintWeather(Temperature &t. Humidity &h). Humidity &h).

. }.K. ‡ A member function can be a friend of any number of classes ©U. class X { void f(). 2008 OOP 92 .R.Member as a friend example class Y { friend void X::f(). }.

. } // perform rest of find } OOP 93 ©U.. if(root->key == key) { // no need to go through an accessor function return root->data.R. // . class BinaryTree { private: Node *root. }. // BinaryTree::key() can now access data directly }.K.. 2008 .Member as a friend example class Node { private: int data. key... friend void BinaryTree::find(int). int find(int key). int BinaryTree::find(int key) { // check root for NULL.

}.R. ‡ A class can be a friend of any number of classes ©U. 2008 OOP 94 . class Y { friend class X.. }.Class as a friend example class X { void f().K.

14 + 2.string concatenation ‡ In C++. ‡ Operator overloading. this is called operator overloading ‡ To overload means give it a meaning for user defined data type. 2008 OOP 95 .floating point addition ³Object´ + ³Oriented" .Operator overloading ‡ Example: the + (plus) operator in C++ behaves differently depending on the operands: 4+5 . which provides simply another way to make a function call for you ©U.0 .K. a way of achieving static polymorphism..R.integer addition 3.

a4 = -a1. ‡ Operators on built-in data types can not be overloaded ©U. a2(10). 2008 OOP 96 . c3 = c1 + c2. String s3 = s1 + s2. String s1(³C++´). c4 = c1+c2*c3.R.operator+(c2). c4 = -c1. c3. 3). c4. c2(3. m2(4. 4).K. 4). 5). m3 = m1 + m2. a3 = a1+a2. C3=c1.. a3. a4.Operator Functions Complex c1(2. Matrix m4 = m1*m2. Array a1(10). m3. if(a1 < a2) { // } Matrix m1(2. s2(³Java´).

Operator Overloading Operators that can be overloaded + ~ /= <<= -new[] ! %= == ->* delete[] * = ^= != -> / < &= <= ..R. % > |= >= [] ^ += << && () & -= >> || new | *= >>= ++ delete ‡ Operators that can not be overloaded · ©U.K. 2008 .* OOP ?: sizeof 97 .

R.K.Operator Functions ‡ Operators can be interpreted as functions in C++ ‡ The number of arguments in the overloaded operator¶s argument list depends on two factors ± Whether it¶s a unary operator or binary operator ± Whether the operator is defined as a global function or a member function ©U.. 2008 OOP 98 .

c4 = -c1. 2008 OOP 99 . o2) or o1. //OR c3 = c1.c4..operator@(o2) Complex c1(2. c3 = c1+c2.5). //will be interpreted as operator-(c1). //will be interpreted as c3 = operator+(c1.Operator Functions ‡ Unary operator @ on object o will be interpreted as operator@(o) or o. c2(3.K.c3.c2).operator@() ‡ Binary operator @ on object o1 and o2 will be interpreted as operator@(o1.operator-() ©U.operator(c2).4). OR c1.R.

.R. 2008 OOP 100 .Operator Overloading ‡ Syntax of Operator overloading as non-member Keyword Operator to be overloaded ReturnType operator OperatorSymbol (argument list) { \\ Function body } ‡ Number of arguments for non-member operator function for ‡ Unary operator ± 1 ‡ Binary operator ± 2 ©U.K.

K.Operator Overloading ‡ Syntax of Operator overloading Class Member ‡ Number of arguments in a member function for ‡ Unary operator ± 0 ‡ Binary operator ± 1 Operator to be overloaded ReturnType classname :: operator OperatorSymbol (argument list) { \\ Function body } ©U.R. 2008 OOP 101 ..

2008 OOP 102 .Unary Operators Overloading ‡ To declare a unary operator function as a nonstatic member return-type operator op() ‡ To declare a unary operator function as a global function ret-type operator op(arg ) ©U..K.R.

4). temp. temp.img = -img return temp. } }. c2 = -c1. Usage: Complex c1(2. img.real = -real..K.Unary ±(minus) operator overloading Using member function class Complex { private: int real. 2008 OOP 103 . public: /*«*/ Complex operator -() { Complex temp.operator -() is called ©U. //c1. c2.R.

a2 = -a1.operator -() is called ©U.i++) temp.R.buf[i]. length.Unary ±(minus) operator overloading class Array { private: int *buf. for(int i=0. return temp. a2. Usage: Array a1(10). //a1. 2008 OOP 104 . public: /*«*/ Array operator -() { Array temp = *this..buf[i] = -temp. } }.length.K.i<temp.

out.operator ++() is called out = ++in. Usage: Index in.. public: /*«*/ // Declare prefix increment operators.R. ©U. ++in. //in. 2008 OOP 105 .K.Pre-increment operator overloading class Index { private: int x. }. Index operator++().

Index operator++(int).operator ++(int) is called in = out++. 2008 OOP 106 ..Post-increment operator overloading class Index { private: int x. }. //out.K.operator ++(int).R. //out. out++. public: /*«*/ // Declare postfix increment operators. out. Usage: Index in. ©U.

R. ++*this. 2008 OOP 107 .. return *this.Implementation? // Define prefix increment operator.K. Point Point::operator++(int) { Point temp = *this. //or ++x. } ©U. return temp. Index Index ::operator++() { x++. } // Define postfix increment operator.

} ©U.real = -c. Complex operator -(const Complex &c) { Complex temp. public: /*«*/ friend Complex operator -(Complex).K. }.real. img. temp.R.img return temp.img = -c. 2008 OOP 108 ..Unary Operators Overloading ‡ Using non-member function class Complex { private: int real. temp.

i<temp.Unary Operators Overloading ‡ Using non-member function class Array { private: int *buf.buf[i] = -temp.i++) temp. 2008 OOP 109 .. public: /*«*/ friend Array operator -(Array). length. for(int i=0. Array operator -(const Array &a) { Array temp = a.K. return temp.length.buf[i]. } ©U. }.R.

int ) // Postfix increment //using friend function friend Index operator++(Index & i) { i. //increment using reader and writer function return i.R.. } //withou using friend function Index operator++(Index & i) { i. 2008 OOP 110 . //i.set(i.K.val()+1).x is private. but friend function can access it return i.Unary Operators Overloading ‡ Using non-member function friend Index operator++(Index & ) // Prefix increment friend Index operator++(Index &. } ©U.x++.

. arg2 ) ©U.Binary Operator Overloading ‡ To declare a binary operator function as a nonstatic member.R. 2008 OOP 111 . you must declare it in the form: ret-type operator op( arg1. you must declare it in the form: ret-type operator op( arg ) ‡ To declare a binary operator function as a nonmember function.K.

} }.r = r+c.Binary + Operator Overloading class Complex { int r.R.K. /*«*/ Complex operator + (const Complex & c) { Complex temp. OOP 112 int main () { Complex c1(2. return temp.. c2(4. i.5). i.r. } ©U. c3=c1*c3.i = i+c. class Complex { public: int r. c3=c1+c2. 2008 . temp.3). c1=c1+c2*c3.i. temp. c3. Complex operator * (const Complex &). public: Complex operator + (const Complex &). }.

int f(Complex x. Complex r2 = x.R. public: Complex operator + (const Complex &).operator+=(y). r2. //r1 = x. } ‡ Computations of r1 and r2 are equivalent ©U. Complex y.K.operator+=(z). //r2 = x.operator+(y. Complex operator += (const Complex &). //r2. i. 2008 OOP 113 . }.operator+(z)). r2 += y. Complex z) { Complex r1 = x+y+z.Binary += Operator Overloading ‡ Minimize number of function directly manipulate objects class Complex { int r.. r2 += z.

2008 OOP 114 .Binary += Operator Overloading ‡ Definition of += is simpler and efficient Complex Complex::operator += (const Complex & c) { r += c.i. } Complex Complex::operator + (const Complex & c) { Complex temp = *this.. i += c. return *this.K.r.R. } ‡ Three objects are involved in a µ+¶ operation ‡ Two objects are involved in a µ+=¶ operation ©U. return temp += c.

2008 OOP 115 .R. Complex operator += (const Complex &). //c2 = operator(2.. Complex operator + (double.Mixed-Mode Arithmetic ‡ To Handle Complex c1 = 2 + c2 we need to define operators of different types class Complex { int r. }. //c1 = x. void f (Complex x. Complex y) { Complex c1 = x+y. i.operator+(y) Complex c2 = 2+x. x) } ©U. const Complex &). public: Complex operator + (const Complex &).K.

K. 2) } ©U.. Complex operator + (const Complex &). Complex operator + (const Complex & . double).operator+(Complex(2)) } class Complex { public: //no one argument constructor }. void f (Complex x) { Complex y = x+2. //y = operator+(x. void f (Complex x) { Complex y = x+2. 2008 OOP 116 .Mixed-Mode Arithmetic ‡ Two ways to Handle Complex c1 = c2+2 class Complex { public: Complex(int).R. }. //y = x.

Complex operator + (const Complex &). double).Ambiguity ‡ Ambiguity may occur of one argument constructor and operator functions both are defined class Complex { public: Complex(int). Complex operator + (const Complex & .R. void f (Complex x) { Complex y = x+2.K. y = x.operator+(Complex(2)) or y = operator+(x.. 2008 OOP 117 . 2)? } ©U. }. //ambiguity.

Explicit Constructor
‡ Implicit conversion can be prevented by declaring constructor explicit
class Complex { public: explicit Complex(int); Complex operator + (const Complex &); }; void f (Complex x) { Complex y = x+2; // error Complex z = x+Complex(2); // ok }

©U.K.R., 2008

OOP

118

Overloading = operator
class Stack { Solution private : int *a, size, top; class Stack { public : public : Stack(int sz) { Stack & operator = (const Stack &s) { top = -1; top = s.top; a = new int[size = sz]; delete a; } a = new int[size = s.size]; void push(int item) { for(int I = 0; I < size; i++) a[++top] = item; a[i] = s.a[i]; } return *this; int pop() { } return a[top--]; }; } };

Stack s1(4), s2(5); s2=s1;

s1 s2

a a

3 6 9 4

s1 s2

a a

3 6 9 4

Before s2=s1
©U.K.R., 2008 OOP

After s2=s1
119

Overloading = operator
class String { private: char *buf; public: int length; String & operator=(const String &); }; String & String::operator=(const String & s) { if(this == &s) return *this; delete buf; length = s.length; buf = new char[length + 1]; strcpy(buf, s.buf); return *this; }

©U.K.R., 2008

OOP

120

Overloading assignment operator
‡ Assignment operator (=) is a binary operator. Its declaration is identical to any other binary operator, Exceptions: ‡ It must be a non-static member function. No operator = can be declared as a non-member function. ‡ It is not inherited by derived classes. ‡ A default operator= function can be generated by the compiler for class types if none exists (bitwise shallow copy) ‡ User defined operator= function performs member wise deep copy.

©U.K.R., 2008

OOP

121

a. X b) { a = b. 2008 OOP 122 . //error: operator= private } ©U. /*«*/ }..R. void f(X.K.Predefined meaning of operators ‡ A default operator= function can be generated by the compiler for class types if none exists (bitwise shallow copy) ‡ Declare it private to make them inaccessible class X { private : X operator=(const X&).

Overloading assignment operator class Point { public: Point &operator=( Point & ).. y = pt. } ©U. // Assignment operator returns left side.. }.. 2008 OOP 123 . x. // Define assignment operator.K. Point &Point::operator=( Point &pt) { x = pt. .R. // Right side is the argument. y. return *this.

int x = t[2][3]. a[4] = 6. 2008 OOP 124 . 5). db["user1"]= "abc". s[0] = µJ¶.[ ] operator Overloading Array a(10). int x = a[4].K. if(db[³user1´] == ³passwdGiven´) { // allow to login } else { // don¶t allow to login } ©U.. db["user3"]= "pqr". t[0][0] = 5. Database db. Table t(4.R. String s(³C++´). db["user2"]= "xyz".

R. Array(int). } Array a(10).operator[](4). a[4] = 6. }. int &operator[] (const int &). //a.[ ] operator Overloading example class Array { private: int *buf.operator[](4) = 6.K. //x = a. 2008 OOP 125 . int &Array::operator[] (const int &index) { return buf[index]. public: int length. ©U. Array().. int x = a[4].

String(). //s. s[0] = µJ¶. public: int length. //ch = s..operator[](0) = µJ¶.R. String(char *).K. char ch = s[1]. }. char &operator[] (const int &).operator[](1).[ ] operator Overloading example class String { private: char *buf. ©U. char &String::operator[] (const int &index) { return buf[index]. 2008 OOP 126 . } String s(³C++´).

} Table t(4. t[0][0] = 5. int).[ ] operator Overloading example class Table { private: Array * buf. public: int row.. Table().K. Array & operator[] (const int &). int x = t[2][3]. 5). Table(int. }. ©U. col. Array & Table::operator[](const int &index) { return buf[index]. 2008 OOP 127 .R.

K. }. }.R. 2008 OOP 128 . Database(). String& operator[](const String&). ©U. const String &v).[ ] operator Overloading example class Pair { public: String name. class Database { private: Pair *list.. Pair(). Pair(const String &n. value. public: int length. Database(const int&).

2008 OOP Database db. list = new Pair[++length].i++) list[i] = p[i]. } } ©U. for(int i=0.[³user´] == ³passwdGiven´) { // allow to login } else { // don¶t allow to login } 129 . for(int i=0. db["user1"]= "abc".name) { index = i. } if(index != -1) return list[index].name = s.R.[ ] operator Overloading example String& Database::operator[](const String& s) { int index = -1. else { Pair *p = list..K. return list[length-1].value.i++) if(s == list[i]. db["user2"]= "xyz". list[length-1].i<length-1. break. db["user3"]= "pqr". if(db.value.i<length.

Friends and Members ‡ Better choice? ‡ Motivation ± Minimize the number of functions accessing representation of a class directly ± Only one choice for constructors.K.R.. 2008 OOP 130 . virtual functions ‡ Function that requires direct access should be a member unless there is a specific reason for it to be a non-member ©U. destructors.

m1(). friend void f1(X&).Friends and Members class X { //« X(int). int m1(). void h() { f1(99). //ok: f3(X(99)). } void g() { 99.m1() not tried //error: X(99). //ok: f2(X(99)).m2() not tried ‡ Operation modifying state should be a member or a global function taking non-const reference ‡ =. f3(99).R. 2008 OOP 131 . } //error: X(99). friend void f2(const X&).. +=. }.m2(). int m2() const. 99. friend void f3(X). //error: f1(X(99)) not tried f2(99).K. function must be non-member taking const reference or non reference ©U. ++ are naturally defined as member ‡ If implicit conversion is desired.

K..R.Friends and Members ‡ If no type conversion is desired. choose member otherwise nonmember ‡ Member call syntax makes it clear to the user that object may be modified. a reference argument is far less obvious ‡ Members are shorter than non-member ©U. there is no compelling reason to choose a member or non-member ‡ Choices depends on function call syntax ‡ inv(m) or m.inv()? ‡ If inv() really inverts m. 2008 OOP 132 .

} ©U. const Matrix& m2) { Matrix temp. Matrix(int).j<4. const Matrix&). return temp.. 2008 OOP 133 .i++) for(int j=0.j++) temp.m[i][j] = m1.R.m[i][j]+m2[i]j].Operators for large objects class Matrix { double m[4][4]. for(int i=0. }. friend Matrix operator+(const Matrix&. Matrix operator+(const Matrix& m1.i<4.K.

Operators for large objects const int MAX 10. const Matrix& m2) { Matrix& temp = get_matrix().j++) temp. static Matrix buf[MAX]. Matrix & get_matrix() { static int index = 0.i<4. } ©U.R.m[i][j]+m2[i]j]. for(int i=0..j<4. 2008 OOP 134 . return temp. } Matrix operator+(const Matrix& m1. return buf[index++].m[i][j] = m1.i++) for(int j=0.K.

K.. ostream& operator<<(int). int x = 2.R. cout << str.h> int main() { char *str = ³C++´. return 1. 2008 OOP 135 . cout << x.operator<<(str).operator<<(x). /*«*/ }. ©U. } //cout.Overloading << operator #include <iostream. ± Consider the simplified version of string I/O from standard library class ostream { ostream& operator<<(const char*). cout. extern ostream cout.

Overloading << operator
#include <iostream.h> int main() { Array a(10), b(3), c(5); String str(³C++´); Table matrix(3, 4); cout << a; //operator<<(cout, a); cout << str; //operator<<(cout, str); cout << matrix; //operator<<(cout, matrix); cout << b << c; //operator << (operator << (cout, b), c) return 1; }

©U.K.R., 2008

OOP

136

<< operator implementation
class Array { /*«*/ friend ostream& operator<<(ostream& os, const Array&); }; ostream& operator<<(ostream& os, const Array&); ostream& operator<<(ostream& os, const Array& a) { for(int i=0;i<a.length;i++) os << a[i] << ' '; return os; }

©U.K.R., 2008

OOP

137

<< operator implementation
class String { /*«*/ friend ostream& operator<<(ostream& os, const String&); }; ostream& operator<<(ostream& os, const String&);

ostream& operator<<(ostream& os, const String& s) { os << s.buf; return os; }

©U.K.R., 2008

OOP

138

<< operator implementation
class Table { /*«*/ friend ostream& operator<<(ostream& os, const Table&); }; ostream& operator<<(ostream& os, const Table&); ostream& operator<<(ostream& os, const Table& t) { for(int i=0;i<t.row;i++) { os << "\n"; os << t[i]; } return os; }

©U.K.R., 2008

OOP

139

istream& operator>>(int). cin. int x .. 2008 OOP 140 . extern istream cin. cin >> str. cin >> x.h> int main() { char str[10].operator>>(x).K.R. return 1.Overloading >> operator #include <iostream.operator>>(str). /*«*/ }. ©U. ± Consider the simplified version of string I/O from standard library class istream { istream& operator>>(const char*). } //cin.

return 1.R. matrix). c). b. //operator>>(cin. cin >> str. a). b). cin >> b << c. //operator>>(cin. str).h> int main() { Array a . } ©U.K. Table matrix.Overloading >> operator #include <iostream. c. //operator>>(cin. cin >> a. String str. 2008 OOP 141 . cin >> matrix.. //operator >> (operator >> (cin.

}. //conversion from char * to String //conversion from Table to Matrix ‡ Convenient but has implication that can be undesirable ©U.Conversion operator ‡ One argument constructor is a conversion operator ‡ It can convert user define/built-in data type to user defined data type class String { public: String(char *). class Matrix { public: Matrix(Table).R. Class Table { /*«*/ }.. 2008 OOP 142 . }.K.

str = ³Java´. } ©U. public: String(char *). void f() { String str(³C++´).K. }. operator char*(). char *s = str. 2008 //conversion to char * //s = char*(str). OOP 143 ..Conversion operator ‡ It can not specify ± User defined to built in conversion ± Conversion from a new class to old class without modifying the old class ‡ User defined conversions are considered when necessary class String { char *buf.R. //in = String(2).

R. out(10). Integer i. } ©U. int x = in. public: Index(int).K. x = 4 //y = int(in) + int(out). int y = in + out in = 2. OOP 144 . 2008 //conversion to int //conversion to Integer //x = int(in).Conversion operator class Index { int i. operator Integer(). y = 14 //in = Index(2) //i = Integer(in).. operator int(). i = in. }. void f () { Index in(4).

Conversion operator class Array { int *buf. int *arr = a..K. operator int*(). public: Array(int). void f () { Array a(10).R. }. 2008 OOP 145 . } //conversion to int* //arr = int*(a) ©U.

i < length.K. 2008 OOP 146 .. return str.Conversion operator Implementation Index::operator int() { return i. } Array::operator int*() { int *temp = new int[length]. } String::operator char*() { char *str = new char[length+1]. strcpy(str. } ©U.R. buf). for(int i = 0. } Index::operator Integer() { return Integer(i). return temp. i++) temp[i] = buf[i].

void h() { f(2).R. // int to Integer conversion }. 2008 OOP 147 .. ambiguous. f(Integer(2)) or f(Index(2)) ? } ©U. Void f(Integer).Ambiguity ‡ An assignment of a value of type V to an object X is legal if ± V is X Or ± there is an unique conversion from V to X class Index { /*«*/ Index(int). class Integer { /*«*/ Integer(int).K. // int to Index conversion }. void f(Index). //error.

y) or x+int(y)? } ©U.. }. //error. void f(int x. 2008 OOP 148 . ambiguous: operator+(Integer(x).Ambiguity ‡ If both user-defined conversions and user-defined operators are defined. it possible to get ambiguity class Integer { /*«*/ Integer(int). // int to Integer conversion operator int(). Integer).R. // Integer to int conversion Integer operator+(Integer. Integer y) { x+y.K.

it must be handled explicitly class Index { /*«*/ Index(int). void h(int i) { f(i). f(Integer(Index(i))) } ©U.R.K.. // Index to Integer conversion }. //ok. Class Integer { /*«*/ Integer(Index). f(Integer(Index(i))) f(Index(i)). // int to Index conversion }. //ok. f(Integer(Index(i))) not tried f(Integer(i)). 2008 OOP 149 . //error.Multilevel conversion ‡ Only one level of user defined implicit conversion is legal ‡ If multiple implicit conversions are required to construct a value. void f(Integer).

}.. //force Integer add } ‡ Programmer should specify the precision to be used ©U. 2008 OOP 150 . Integer). double d2) { Integer q1 = d1 + d2.R. Integer operator +(Integer. //double precison add Integer q2 = Integer(d1) + d2.Other issues ‡ Return type is not used as overload resolution class Integer { public: Integer(double). vid f(doube d1.K.

double(). int i = r.int(). // i = r. both types are used to resolve resolution class Real { public: operator double(). operator int(). i = r. // i = r. 2008 OOP 151 . d = r. // d = r.Other issues ‡ If both sides of an assignment or assignment have been determined. // d = r..double().int() } ©U.K. }. void f(Real r) { double d = r.R.

they lead to ambiguity ‡ Rely on either user-defines conversions or user-defined operators. 2008 OOP 152 .K. but not both ©U.Things to remember ‡ It is not a good idea to define a conversion operator without significant reason ‡ When used in excess..R.

2008 // operator new(sizeof(int)). // operator new(sizeof(double))..R. OOP 153 .Overloading new operator int *x = new int. ©U. // *x = ? // *f = ? // *d = ? ‡ Standard implementations of new and new[] do not initialize memory returned ‡ Default behavior can be overridden by redefining new operator void * operator new (size_t sz). float *f = new float. float *f = new float. // operator new(sizeof(float)).K. double *d = new double. double *d = new double. int *x = new int.

2008 OOP 154 . for(int i = 0..new operator implementation void * operator new (size_t sz) { void * temp = malloc(sz). return temp. i < sz. } ©U.K.R. i++) ((char *)temp)[i] = 0.

. consequenctly it does not have this pointer ©U. 2008 OOP 155 .new operator for class Point *p = new Point.R. it calls Point¶s default constructor ‡ Specialized allocator/deallocator for a class can be provided class Point { public: void *operator new(size_t).K. ‡ operator new is implicitly static. }. ‡ Calls operator new(sizeof(Point)) or Point::operator new(sizeof(Point)) ‡ If new operator call is successful (memory allocation is successful).

} } return temp.. } ©U. 2008 OOP 156 . return NULL.K. if(temp == NULL) { cout << "Memory exhausted\n".new operator for class ‡ Implementation void * Point::operator new (size_t sz) { void * temp = malloc(sz). if(temp == NULL) { //try to find some free memory void * temp = malloc(sz).R.

Overloading new[ ] operator ‡ Default behavior can be overridden by redefining new operator int *x = new int[2].. ©U. // operator new[](sizeof(float)). int *x = new int[2]. x[1] = ? // f[2] = ? // d[4] = ? void * operator new[] (size_t sz). // operator new[](sizeof(double)). // x[0]. double *d = new double[10]. // operator new[](sizeof(int)). float *f = new float[4].K. 2008 OOP 157 . float *f = new float[4].R. double *d = new double[10].

for(int i = 0.K. i < sz. return temp. } ©U..R.new[ ] operator implementation void * operator new[ ] (size_t sz) { void * temp = malloc(sz). i++) ((char *)temp)[i] = 0. 2008 OOP 158 .

Overloading delete operator ‡ Deallocates memory allocated by new void operator delete (void *).K. void operator delete (void *p) { if(p) { // deallocate memory allocated by new. 2008 OOP 159 .R.. } } ©U.

}. public: int& operator() (const int &. ‡ Implementation int& Table::operator() (const int &i. 5).. 3) = 8. const int &j) { return buf[i][j]. int x = matrix(4. const int &). 2008 OOP 160 .K. } ©U. 10).Overloading () operator ‡ One popular use of () operator is as subscripting operator for multidimensional arrays class Table { int ** buf. matrix(2.R. Table matrix(10.

} Point p(3. ©U. const int &).R. const int &yy) { x = xx. y = yy. public: void operator() (const int &. 2008 //object used as a function OOP 161 . 5).K. y. }.. p(4.Overloading () operator ‡ Function Objects ± Objects used as a function class Point { int x. 4). void operator() (const int &xx.

} // (p.operator->())->m = 2.Overloading operator ‡ Dereference operator can be used as unary postfix operator ‡ Given a class class Ptr { public: X* operator->().K.. 2008 OOP 162 .R. Objects of Ptr can be used to access members of class X in a very similar manner to the way pointers are used void f(Ptr p) { p->m = 2. ©U. }.

public: Point().6). void setx(int). Point(int. int). y. 2008 OOP 163 . ©U. operator class PPtr { Point *ptr. }.R. }. PPtr(Point &).K. p1(5. PPtr pp(p1). Point* operator->(). cout << pp->getx(). public: PPtr().Overloading ‡ Example class Point { private: int x.. int getx().

©U. APtr ptr(*a). ptr->length. 164 ..Overloading operator ‡ For ordinary pointers. Array& operator[](int). 2008 OOP Array *a = new Array[4].m == p[0]. }. for(i = 0.m ‡ Such gurantee is not provided for user-defined operators class APtr { Array *arr. APtr(Array &). ptr++.i<4.K. cout << *ptr. Array& operator++(). Array* operator->(). use of -> is synonymous with some uses of unary * and [].R. Given Y *p it holds that p->m == (*p). Array& operator*().i++) cout << ptr[i]. public: APtr().

b3 = b1 ^ b2. Bit operator&(Bit). Bit& operator!().b. public: Bit(). Bit operator|(Bit). Bit Bit::operator|(Bit bit) { Bit temp. b3 = b1 | b2. b2(0).. Bit operator^(Bit). ©U. } Bit b1(1).b = b|bit. 2008 OOP 165 . b3 = b1 & b2. b3 = !b1. b3.Bitwise operator overloading class Bit { char b:1. }. Bit(int).R.K. return temp. temp.

Inheritance ‡ By using the concepts of inheritance.R.. 2008 OOP 166 . relationship. ‡ Inheritance provides a mechanism for class level Reusability. ‡ Semantically.K. it is possible to create a new class from an existing one and add new features to it. inheritance denotes an ³is-a´ ©U.4.

Qual. Course Marks Teaching Staff Edn.No. 2008 OOP 167 .Inheritance Person Name Height Age Student Reg.R.K. ©U. ³Student´ is a specialization of ³Person´. Designation Specialization ³Person´ is a generalization of ³Student´..

.K. ‡ Attributes and operations common to a group of subclasses are attached to the superclass and shared by each subclass. ©U. 2008 OOP 168 . ‡ The class being refined is called the superclass or base class and each refined version is called a subclass or derived class.Inheritance ‡ Inheritance is the relationship between a class and one or more refined version of it.R. ‡ Each subclass is said to inherit the features of its superclass.

‡ The visibility-mode is optional. ‡ It may be either private or public or protected(default it is private) ‡ This visibility mode specifies how the features of base class are visible to the derived class.K..// members of the derived class }.Defining Derived Class ‡ The general form of deriving a subclass from a base class is as follows class derived-class-name : visibility-mode base-class-name { «««««« // ««««««. 2008 OOP 169 . ©U.R.

Inheritance Types of Inheritance ‡ Simple or Single Inheritance ‡ Multi level or Varied Inheritance ‡ Multiple Inheritance ‡ Hierarchical Inheritance ‡ Hybrid Inheritance ‡ Virtual Inheritance ©U.K.R. 2008 OOP 170 ..

class Student : public Person { /*«*/ }. Student subclass(derived class) visibility mode ©U..Simple or Single Inheritance ‡ This a process in which a sub class is derived from only one superclass. ‡ a Class Student is derived from a Class Person superclass(base class) Person class Person { /* «*/ }.K. 2008 OOP 171 .R.

Person class Person { /*«*/ }. ‡ A derived class CS-Student is derived from another derived class Student. OOP 172 Student CS -Student ©U.R..Multilevel or Varied Inheritance ‡ The method of deriving a class from another derived class is known as Multiple or Varied Inheritance. class CS -Student : public Student { /*«*/ }.K. class Student : public Person { /*«*/ }. 2008 .

K. class Student { /*«*/ }.Multiple Inheritance ‡ A class is inheriting features from more than one super class ‡ Class Part-time Student is derived from two base classes.. 2008 . OOP 173 Employee Student Part-time Student ©U.R. class Part-time Student : public Employee. Employee and Student class Employee { /*«*/ }. public Student { /*«*/ }.

2008 . class Person { /*«*/ }.K..R. OOP 174 Person Student Employee ©U. class Student : public Person { /*«*/ }.Hierarchical Inheritance ‡ Many sub classes are derived from a single base class ‡ The two derived classes namely Student and Employee are derived from a base class Person. class Employee : public Person { /*«*/ }.

more than one type of inheritance are used to derive a new sub class ‡ Multiple and multilevel type of inheritances are used to derive a class PG-Student class Person { /*«*/ Person }. class PG . class Gate Scorer { Student Gate_Scorer /*«*/ }.Student : public Student public Gate Scorer { PG_Student ©U.R. 175 .K. 2008 /*«*/ OOP }.Hybrid Inheritance ‡ In this type. class Student : public Person { /*«*/ }..

2008 OOP 176 . class Student : public Person { Student Employee /*«*/ }. Part-time Student class Part-time Student : public Student.K.R. public Employee { /*«*/ }..Virtual Inheritance Person class Person { /*«*/ }. Class Employee : public Person { /*«*/ }. ©U.

Virtual Inheritance ‡ A sub class is derived from two super classes which in-turn have been derived from another class.R. Student and Employee.. ‡ The class Part-time Student inherits. 2008 OOP 177 .K. the features of Person Class via two separate paths ©U. ‡ These classes in-turn derived from a common super class Person. ‡ The class Part-Time Student is derived from two super classes namely.

. 2008 OOP 178 . subclasses inherit behavior.R. ± Super class specifies behavior. ©U.Inheritance cont¶d«. ± Super class legislates an abstract behavior and therefore delegates implementation to super class. subclasses choose to override behavior. ± Super class specifies behavior.K. so each subclass adds its own behavior. Four things you might find in an Inheritance Hierarchy ± Super class is too general to declare all behavior.

2008 OOP 179 .K. then we can choose access specifier protected.R.Access Specifiers with Inheritance ‡ If we want an instance variable to be available for subclasses to change it.. ©U. ‡ The following examples illustrates the usage of these access specifiers.

public: int publ. //Ok publ =1. }. //Error : prot is protected //and the function global_fun( ) // is not a friend or a member of X or Y p->publ =3. publ = 3. void X::m( ) { priv =1.. //Error : priv is private of X p->prot = 2. //Ok prot =1. void m( ). prot = 2. 2008 Y::mderived( ) { priv =1. protected: int prot.Access Specifiers with Inheritance class X { int priv. // Ok } OOP 180 .R. //Error priv is private and //cannot be inherited // Ok // Ok } void global_fun(Y *p) { p->priv = 1. }. //Ok } class Y : public X { void mderived( ).K. ©U.

Public Derivation ©U. int a3. int b2 public: int b3. Protected and Private derivation Class A private : int a1. Class B: Public A private : int b1. protected: int a2.K.R. 2008 OOP 181 . Class B private : int b1.. public : int b3. public : int a3. protected : int a2. protected : int b2.Public.

2008 Y::mderived( ) { priv =1. }. //Ok prot =1.K. void m( ).Public derivation .. public: int publ. void X::m( ) { priv =1. prot =2. //Ok } class Y : public X { void mderived( ).example class X { int priv. //Error : prot is // protected and the function global_fun( ) // is not a friend or a member of X or Y p->publ =3. //Error priv is private and //cannot be inherited // Ok // Ok } void global_fun(Y *p) { p->priv = 1. protected: int prot. }. ©U. //Error : priv is //private of X p->prot = 2.R. //Ok publ =1. // Ok } OOP 182 . publ=3.

R. protected : int b2. protected: int a2.example ‡ The inherited public and protected members of a base class become protected members of the derived class Class A private : int a1. Class B private : int b1. protected : int a2. public: int b3. public : int a3. Class B : Protected A private : int b1.Protected derivation . int b2.K. public : int b3. Protected Derivation ©U. 2008 OOP 183 ..a3.

}. public: int publ. //Ok prot =1. protected: int prot. ©U.R. // Ok } void global_fun(Y *p) { p->priv = 1. //Error : priv is //private of X p->prot = 2.example class X { int priv..Protected derivation . protected } OOP 184 .K. void m( ). //Ok publ =1. // Ok publ=3. // Error. //Error priv is private and //cannot be inherited prot =2. 2008 Y::mderived( ) { priv =1. //Error : prot is //protected and the function global_fun( ) // is not a friend or a member of X or Y p->publ =3. }. void X::m( ) { priv =1. //Ok } class Y : protected X { void mderived( ).

Private Derivation ©U.R.Private derivation . protected : int b2.. 2008 OOP 185 . public : int b3. Class B private : int b1. int a1.example The inherited public and protected members of a private derivation become private members of the derived class. protected: int b2. public: int b3. Class A private : int a1.K. public : int a3. protected : int a2. Class B : private A private : int b1.a2.a3.

Y::mderived( ) { priv =1. }. //Error priv is private and //cannot be inherited prot =2.. 2008 } class Z: public Y { public : void f() { prot=2. //Ok prot =1.//error. //Error : priv is //private of X p->prot = 2. // error } OOP 186 .example Class X { int priv. protected: int prot. }. void global_fun(Y *p) { p->priv = 1. void m( ). //Error : prot is //protected and the function global_fun( ) // is not a friend or a member of X or Y p->publ =3. // Ok ©U. public: int publ. //Ok } class Y : private X { void mderived( ). void X::m( ) { priv =1.K.R. // Ok publ=3. prot is private to Y } }. //Ok publ =1.Private derivation .

R.. ‡ If base class does not have default constructor. derived class constructor has to invoke base class constructor explicitly.Derived Class Constructors ‡ A base class constructor is invoked.K. 2008 OOP 187 . when a derived class object is created. ‡ Constructor of the base class will invoked before constructor of derived class ©U.

Derived Class Constructors class B { int x. void main( ) { D d. public : B( ) { cout << ´B::B( ) Fires«´ << endl. } }. class D : public B { int y. } ©U.K. 2008 OOP B::B( ) Fires« D::D( ) Fires« 188 . } }. public : D( ) { cout << ´D::D( ) Fires«´ << endl..R.

} }. int y) : B(y) { b =x.} D(int x. public : B( ) { a = 0. int) Fires«´<<endl.R. cout<<´B::B(int) Fires«´<<endl. cout<<´D::D(int) Fires«´<<endl. class D : public B { int b.} B(int x) { a =x. cout<<´D::D(int. cout<<´B::B( ) Fires«´<<endl. D d(10). D d(10..K. public : D( ) { b =0.Derived Class Constructors class B { int a. int) Fires« 189 . } ©U. } }. void main( ) { D d.} D(int x) { b =x. 20). 2008 OOP B::B( ) Fires« D::D( ) Fires« B::B( ) Fires« D::D(int) Fires« B::B(int) Fires« D::D(int. cout<<´D::D( ) Fires«´<<endl.

class D : public B { int y.} ~B( ) { cout<<´B Destructor Invoked «´<<endl. public : D( ) { cout<<´D Constructor Invoked «´<<endl.R. void main( ) { D d.Derived Class Destructors ‡ Derived class destructors are called before base class destructors.} }.K. } B Constructor Invoked« D Constructor Invoked« D Destructor Invoked« B Destructor Invoked « ©U.} }. class B { int x. 2008 OOP 190 ..} ~ D( ) { cout<<´D Destructor Invoked«´<<endl. public : B( ) { cout<<´B Constructor Invoked«´<<endl.

Manager m(³Mike´. need to be redefined sometimes. //Employee::printDetails invoked } class Employee { protected : char name[50]. function inherited from base class. //Employee::printDetails invoked m.cout << type. //Manager::printDetails invoked OOP 191 .printDetails(). 2008 m. } } ©U.K.printDetails(). } class Manager : public Employee { public : void printDetails() { Employee::printDetails().. When the same function exists in both the base class and the derived class. } class Manager : public Employee { protected: int type. public : void printDetails() { cout << name.printDetails().Overriding Member Functions ‡ ‡ In the derived class. the function in the derived class is executed on derived class object void main( ) { Employee e(³John´). e.1).R.

R. Objective: ± After completing this module.you will be able to understand.5.K..e Polymorphism is discussed. ± Static Polymorphism ± Overloaded Functions ± Overloaded Operators ± Dynamic Polymorphism ± Virtual Functions ©U. 2008 OOP 192 . Polymorphism Introduction: In this Module one of the most important concept of OOPS i.

polymorphism means that some code or operations or objects behave differently in different contexts ‡ It provides a single interface to entities of different types. 2008 OOP 193 .K..R. many or multiple ‡ In programming languages.Polymorphism ‡ Greek word meaning forms. ©U.

2008 OOP 194 .R.Types of polymorphism Polymorphism Static Polymorphism Dynamic Polymorphism Function Overloading Operator Overloading Virtual Function ©U.K..

R. 2008 OOP 195 .K..Polymorphism ‡ Compiler determines a location in memory is called binding ‡ Connecting a function call to a function body is called Binding ‡ The location may represent the following ± Variable names bound to their storage memory address (offset) ± Function names bound to their starting memory address (offset) ‡ Two kinds of binding ‡ Compile-Time Binding ‡ Run-Time Binding ©U.

Static Polymorphism ‡ Compile-time binding or early binding is called as static polymorphism. 2008 OOP 196 .R.K. ‡ Compile-Time Binding means ± Compiler has enough information to determine an address (offset) ± Named variables have their addresses hard-coded during compilation ‡ Global variables are given offset from start of global data area ‡ Local variables are given offset from top of stack ‡ Objects are given offset from start of object data ± executable code contains address references ©U..

‡ Compact way to make overloaded functions ‡ Instantiation²Generate separate functions for different data types.R. ‡ Until certain point they fulfill the functionality of a macro. 2008 OOP 197 .Function Templates ‡ To create generic functions that admit any data type as parameters and return a value without having to overload the function with all the possible data types.K. ©U..

} ©U. primitive or user-defined template < class identifier > ReturnType FunctionName(arguments of type identifier) template < class T > // or template< typename T > T square( T value1 ) { return value1 * value1.Function Templates Keyword for declaring function template Keyword class Name of the template data-type Function parameters of type template.R.K.. 2008 OOP 198 .

2008 OOP 199 ..K.Function Templates Examples: Finding the absolute value of a variable Prototype (Declaration): template <class Type> Type abs(Type val). Definition: template <class Type> Type abs(Type val) { if (val >= 0) return val. else return ±val. } ©U.R.

C C ©U.1. int2. char2. 1. T value2. 2. if ( value2 > max ) max = value2. 2.K. double2.R..1 .Function Templates // definition of function template maximum In main( ) template < class T > maximum( int1. int3 ) // or template < typename T > T maximum( T value1. T value3 ) { maximum( double1.8 2. if ( value3 > max ) max = value3. 2008 OOP 200 . B. 3 3 1. maximum( char1.1 A. char3 ) return max. double3 ) T max = value1. } Output Maximum value Input values 1.

R.Function Template Overloading ‡ Other function templates with same name ± Different parameters template<class T> T sqrt(T). 2008 OOP 201 . sqrt(1). //sqrt<double>(complex<double>) //sqrt<double>(complex<double>) is more specilized than sqrt<complex<T>>(complex<double>) template<class T> class complex { T real. double sqrt(double). ©U. //sqrt<int>(int) sqrt(2. function template generates function-template specialization and uses most specialized one complex<double> z. template<class T> complex<T> sqrt(complex<T>). img.K. /*«*/ }.0). ‡ Non-template functions with same name ± Different function arguments ‡ Compiler performs matching process ± Tries to find precise match of function name and argument types ± If fails. //sqrt(double) sqrt(z)..

‡ Fails to compare two strings template<> bool less<const char*>(const char *a. const char *b) { return strcmp(a.b).5). const char *b) { return strcmp(a. } ©U. } less(2.Template Function Specialization ‡ By default a template gives a single definition to be used for every template argument²does not make sense always template <class T> bool less(T a.R.5). less(3.. 1. ³Java´). T b) { return a<b?true:false. less(³C++´.b). } 202 .4. } template<> bool less<>(const char *a. 2008 OOP template<> bool less(const char *a. const char *b){ return strcmp(a.K.b).

Template Function Specialization ‡ Another example class Stack { int size. } //swap for Stack template<> void swap(Stack &a. } ©U. T &b) { T temp = a..R.a). s. Stack operator=(const Stack&).K.top).size). s2(2000). s. s2). b = temp. s. a = b. } void Stack:::swap(Stack &s) { swap(size. *a. swap(s1. //inefficient template<class T> void swap(T &a. Stack &b) { a. swap(a. top. /*«*/ } Stack s1(1000). 2008 OOP 203 . swap(top.swap(b).

int x.R. i=x.K. 2008 //char * to String conversion //String to char* conversion OOP 204 . ©U. x=i. char *str=lang. } //int to Index conversion //Index to int conversion //int to Index conversion Another Example main( ) { String lang(³C++´)..Type Conversion An Example main( ) { Index i(3).

. 2008 Not applicable Casting Operator Casting operator OOP Constructor Not Applicable Constructor 205 .K. This process is called conversion by constructor ‡ Objects can also be converted by user-supplied conversion functions Conversion required Conversion takes palce in Conversion takes palce in Basic class Class basic Class class ©U.Type Conversion ‡ Objects of a given class type can be converted to objects of another type ‡ This is done by constructing an object of the target class type from the source class type and copying the result to the target object.R.

main( ) { Index i(3). int x. } ©U..Type Conversion class Index { int x. public : Index(int i):x(i){} operator int() { return x. x=i. 2008 //Index to int conversion operator //int to index conversion //x=int(i) //i=Index(x) OOP 206 . i=x.K.R. } }.

.Type Conversion #include <string.s). s ). //String to char* conversion } 207 . 2008 OOP int main() { String s( "abcd" ). }. } } private: char _text[80]. char*(s)).R.h> class String { public: // Define constructor that converts //from type char * String( char *s ) { strcpy( _text. //strcpy(str. } // Define operator conversion function //to type char * operator char *() { return _text. strcpy(str. ©U.K. char *str = "efgh".

(i)It can convert ch to an object of type String using the constructor and then perform the comparison using the user-defined operator==. String ) . private: char _text[80].Ambiguity During Type Conversion #include <string.K. 2008 OOP 208 . int main() { String s( "abcd" ). char *ch = "efgh".R. }. (ii)It can convert s to a pointer of type char * using the conversion function and then perform a comparison of the pointers. bool operator==(String ..h> class String { public: String( char *s ). operator char *(). The compiler has two choices and no way of determining which is correct. String(ch)) or char*(s) == ch ? }©U. //ambiguity operator ==(s. return s == ch.

Index). i) or x+int(i) ? } ©U. x+i. public : Index(int i):x(i){} operator int() { //Index to int conversion operator return x.Ambiguity During Type Conversion class Index { int x. main( ) { Index i(3). operator(Index(x).K.R. int operator +(Index.. } }. int x. //ambiguity. 2008 OOP 209 .

Composition ‡ Classes having objects of other classes as their data members .} int g() const { return i..K. public: X x.set(10). Y() { i=0. 2008 OOP int i.x.} void f(int j) { i=j. } void set(int j) { i = j. ©U. } }. public: x() { i = 0. int main() { Y y. } int read() const { return i. y.f(5).composite classes class y { class X { int i.R.} }. y. } 210 .

} Output : Y¶s constructor X¶s constructor Z¶s constructor OOP 211 ©U. class Z { int k. public: X(int ii=0):i(ii) { cout << ³X¶s constructor´. }. } int main() { Z z(1..2. y(b).R. public: Y y. X x. }. 2008 .K. int c) : x(a). class Y { int j. k(c) { cout << ³Z¶s constructor´. Z(int a.3).Constructors in Composite Class class X { int i. }. }. public: Y(int jj=0):j(jj) { cout << ³Y¶s constructor´. int b.

f().. // B::f(). void main(){ D d. }. //obvious d. // B::f(). //B::f().R. 2008 OOP No matters style of call. call f() through a base class pointer } ©U.K.Polymorphism : Non±Virtual Functions ‡ Base class Pointer can point an object of its subclass ‡ Base class reference can refer an object of its subclass class B{ public: void f(). All three calls of f( ) on derived class object d through the object. function name and object type serve as basics for function body selection. class D: public B{ public: // f() not overridden }. //obvious B*pd = &d. D*pb = &d. through a base class pointer and through a derived class pointer provides the same result. 212 . call f() through a derived class pointer pb->f(). call f() through d pd->f().

} class Manager : public Employee { protected: int type.Polymorphism : Non±Virtual Functions class Employee { protected : char name[50]. public : void printDetails() { cout << name. public : void printDetails() { Employee::printDetails().. //Employee::printDetails } OOP 213 .R. 2008 void main( ) { Employee e(³John´).//Employee::printDetails() eptr = &m. cout << type.//legal as Manager is an Employee eptr->printDetails(). Manager m(³Mike´. eptr = &e. //obvious eptr->printDetails(). *eptr. } } ©U.K.1).

arr[1] = new Rectangle.Polymorphism : Non±Virtual Functions class Shape { public : void draw(). ©U. class Rectangle : public Shape { public : void draw(). }.i<3. class Circle : public Shape { public : void draw().K. }. arr[2] = new Circle. }. 2008 void main( ) { Shape *arr[3].i++) //draw all objects arr[i]->draw(). class Triangle : public Shape { public : void draw().. for(int i=0. }. } OOP 214 .R. arr[0] = new Triangle.

.R.K. The redefined virtual function implements a specific method. ©U. ‡ A virtual function defines a general class of actions . ‡ For non-virtual functions with the same name. 2008 OOP 215 .Polymorphism : Virtual functions Virtual Functions ‡ A member function that is declared as virtual in a base class and redefined by a derived class. ‡ For virtual methods with the same name the system determines at run time which of the methods to invoke. the system determines at compile time which of the function to invoke.

class D : public B { public: void g(). }. }. 2008 OOP 216 .R. int main() { D d. B::h invoked ptr->g(). D::h invoked } ©U. B *ptr = &d. int h(). ptr->h(). int h().K.Virtual Functions : Example 1 Class B { public: virtual void g()..

\n´.Virtual Functions : Example 2 class Base { public: virtual void fun() {cout<<´This is base fun(). class Derived1 : public Base { public: void fun() { cout<<´ This is derived1 fun() . class Derived0 : public Base { public: void fun() {cout<<´ This is derived0 fun(). } 217 .. ptr->fun().\n´. Derived0 D0.} }. ptr->fun(). ptr=&D1. Derived1 D1.K. } }.R.\n´. p->fun(). ptr=&B. ptr=&D0. } }. return 0. Output This is base fun() This is derive0 fun() This is derive1 fun() ©U. 2008 OOP int main() { Base *ptr B.

Virtual Functions : Constructors

‡ Virtual functions should be member functions. ‡ To construct an object , a constructor needs the exact type of the object it is to create. ‡ So a constructor can not be virtual but a destructor can be.

©U.K.R., 2008

OOP

218

Virtual Functions : Constructors contd«
class B { public: B( ) { this->f(); } virtual void f() { cout<<´Executing B::f()´<<endln; } };

main() { D d; cout<<´object d was created successfully´<<endl; d.f(); }

class D: public B { public: D( ){ } virtual void f( ) { cout<<´Executing D::f()´<<endl; } };

output
Executing B::f() object d was created successfully. Executing D::f()

©U.K.R., 2008

OOP

219

Virtual Functions : Destructors
class B { char * ptrB; public: B() { ptrB = new char[5]; cout<<´B allocates 5 bytes\n´; } ~B() { delete[] ptrB; cout<<´B frees 5 bytes\n´; } }; class D: public B { char*ptrD; public: D( ) : B() { ptrD=new char[1000]; cout<<´D allocates 1000 bytes\n´; } ~D() { delete[] ptrD; cout<< ³ D frees 1000 bytes\n³; } };

©U.K.R., 2008

OOP

220

Virtual Functions : Destructors contd«
void main() { while(1) f(); } void f() { B*p=new D; delete p; } The Memory will be exhausted, in each call of function f( ), B allocates 5 bytes D allocates 1000 bytes B frees 5 bytes.

As p is of type B*, p is bound to B¶s data members and methods, including constructors and destructors rather than to D¶s methods . When f exits B::~B frees the 5 bytes. D::~D() fails to fire.

©U.K.R., 2008

OOP

221

. cout<<´B frees 5 bytes\n´. public: B() { ptrB=new char[5]. 2008 OOP 222 . } }. } virtual ~B() { delete []ptrB. cout<< ³ D frees 1000 bytes\n³. ©U.K. cout<<´B allocates 5 bytes\n´. cout<<´D allocates 1000 bytes\n´. } ~D() { delete[] ptrD.Solution class B { char * ptrB. public: D( ) : B() { ptrD=new char[1000]. class D: public B { char*ptrD.R. } }.

return ival.K. ©U. return ival. class Derived :: public Base{ public: virtual int foo(int ival=2048) { cout<<´derived::foo() ± ival :´ << ival << endl. rather it is determined at compile time and is based on the type of the object through which the function is being invoked. } }.R. } }.Virtual Function : Default Arguments The default argument is not determined at run time. 2008 OOP 223 . class Base { public: virtual int foo(int ival=1024){ cout<<´base::foo()²ival :´<<ival <<endl..

Virtual Function : Default Arguments contd« int main () { Derived *pd=new derived. rather it is determined at compile time and is based on the type of the object through which the function is being invoked. Base *pb=pd. val = pd->foo(). int val = pb->foo(). ©U.. cout<<´main : val through derived ³<<val<<endl. 2008 OOP 224 . } Output derived:: foo() ± ival : 1024 main : val through base : 1024 derived :: foo() ± ival : 2048 main : val through derived : 2048 The default argument to be passed to foo() is not determined at run time.K. cout<<´main : val through base ³ <<val<<endl.R.

no instance of the class can be created.. ± If a base class declares a pure virtual functions . ©U. 2008 OOP 225 . each of which generally provides a different definition.K.R. ± no instance of an abstract base class are ever created. and so it is necessarily an abstract base class.Abstract Class & Pure Virtual Functions Abstract Class ± A class that serves only as a base class from which other classes can be derived . Pure Virtual Functions ± A virtual function that is declared in a base but not defined there . ± responsibility for defining the function falls on the derived classes.

class Derv1 : public Base { public: void show(){ cout<<´\n Derv 1´.Pure Virtual Function class Base { public: virtual void show()=0.K.. } }. } }. void main(){ Base *List[2]. // Pure Virtual function }.R. class Derv2 : public Base{ public: void show(){cout<<´\n In Derv2´. List[1]=&dv2. Derv2 dv2. List[0]=&dv1. 2008 . Derv1 dv1. List[1]->show(). List[0]->show(). } OOP 226 ©U.

// Pure Virtual function }. class Circle : public Shape2D { public: void draw(). class Shape2D : public Shape { public: virtual float area()=0. // Pure Virtual function }. // Pure Virtual function }. float volume(). // concrete functions }.K. // concrete functions }. 227 . 2008 OOP class Shape3D : public Shape { public: virtual float volume(). ©U.. float area(). class Cube : public Shape3D { public: void draw().R.Pure Virtual Function class Shape { public: virtual void draw()=0.

}.Virtual Function & Private/Protected Derivation Polymorphism does not work with private or protected derivation class Base{ public: virtual void f(). Always use public inheritance with polymorphism. }. OOP 228 . // ok ptr->f(). Base *ptr. class Derived : private Base{ public: void f().K. ptr=&d. Derived d.. b. 2008 Standard conversions don¶t convert derived class pointers to base class pointers with private/protected derivation. // illegal ptr=&b.R. // calls B::f() ©U.

Virtual Function Implementation ‡ Most compiler build a virtual function table for each polymorphic class. All object of the same class share the same virtual function table(vtable). 2008 OOP 229 . ‡ The value of the pointer depends on whether or not the derives class override a base class virtual function with a new version of its own.K. ‡ The vtable is an array of pointers to virtual functions that have definitions in either a base class or a derived class . ©U. ‡ A polymorphic class with at least one virtual function includes a hidden pointer (vptr) to its object which points to vtable.R..

Base Members vptr Derived Members Derived vtbl.K. Base Members vptr Base::f2() Base::f3() Derived d1.Virtual Function Implementation contd« Base vtbl. 2008 OOP 230 . Base::f1() Derived::f2() Base::f3() Derived::f4() ©U.. Base::f1() Base b1.R.

} virtual void f4() { cout<<Derived ::f4()´<. // illegal Derived *q=&d1. 231 . p->f4().Virtual Function ± Example 4 class Base{ public : Base() { } virtual void f1() { cout<<´base::f1( )´ << endl. q->f4() . Derived d1. } }.R. } virtual void f2( ) { cout << Base:: f2()´<<endl.endl.K.. Base *p=&d1. we can¶t access any derived class members. ©U. 2008 OOP Base b1. } virtual void f3() { cout<<´Base :: f3()´<<endl.} }. class Derived { public: Derived() { } void f2() { cout<<´Derived ::f2()´<<endl.// legal With the help of base class pointer.

kbcafe.html http://www.K.bitpipe.com/codecuts/p All dfs/ooc.de/gna/html/cc/Tutor All ial/tutorial.R.planetpdf.com/rlist/term/Obj ect-Oriented-Programming. 2008 OOP 232 .html All http://www.com/user/ritchie/oo.well.desy. Concepts.pdf Reference Topic or Module All All All http://www.h All tml http://www.com/articles/OOP.Object Oriented Programming: Next Step ll Book Book PDF URL Description OO A & D by Grady Booch Object oriented software concepts by Bertrand Mayer http://www.pdf ©U..

Congratulations! You have successfully completed Object Oriented Programming ©U..K.R. 2008 OOP 233 .