Académique Documents
Professionnel Documents
Culture Documents
Session 3 : 4th Sep, 15.30 17.45 Session 4 : 5th Sep, 10.55 12.45 Session 5 : 5th Sep, 15.30 17.45 Session 6 : 6th Sep, 10.55 12.45 Session 7 : 6th Sep, 15.30 17.45
TEST Inheritance Polymorphism, Function Overloading, Operator Overloading, Virtual functions.
OOP concept was developed in late 70s Simula67, Smalltalk, Lisp, Clu, Actor, Eiffel, Objective C
Main Program
Function - 1
Function - 2
Function - 3
Function - 4
Function - 5
Summary of POP
Large programs are divided into smaller program known as functions.
Most of the function share global data. Data move openly around the system from function to function. Emphasis is on doing things. Employs top-down approach in program design.
9
Object-Oriented Concepts
Objects are the physical and conceptual things we find in the universe around us. Like a person, a place, a bank account etc.
Object Oriented means that we organize software as a collection of discrete objects that incorporate both data structure ( member variables ) and behavior ( Methods ). Object Oriented Programming is a programming style that captures the behavior of the real world in a way that hides detailed implementation.
11
Object-Oriented Concepts
What is Class?
A Class is a user defined data type that defines member variables and the member functions common to all objects of a certain kind.
A class contains variables and methods. The values of the variable define the state of the object and the methods define the behavior of the object.
Member Function (Methods) Member Variables (Variables) Object is an instance of class.
12
Object-Oriented Concepts
13
Object-Oriented Concepts
14
Object-Oriented Concepts
Need for classes
Classes are needed to represent real-world entities (objects) that are not only have data type properties (their characteristics) but also associated operations (their behavior).
15
Object-Oriented Concepts
Object Oriented Paradigms:
There are four main object oriented principles which are important to an overall object oriented approach.
16
Object-Oriented Concepts
Encapsulation
The wrapping up of data and functions (that operated on the data) into a single unit (called class) is known as encapsulation. Also known as Data Hiding. The data is not accessible to the outside world and only those functions which are wrapped into the class can access it.
17
Object-Oriented Concepts
Abstraction
This is a process of design which allows us to ignore details. Abstraction allows question such as What can it do? rather than How is it going to do?
18
Object-Oriented Concepts
Example:
Class LightSource { Public : LightSource(); Void TurnOn(); Void TurnOff(); }
19
Object-Oriented Concepts
Inheritance
Inheritance is the process by which objects of one class can acquire the properties of objects of another class.
20
Object-Oriented Concepts
21
Object-Oriented Concepts
Inheritance and Reuse
C++ supports the idea of reuse through inheritance. A new type can be declared, which is an extension of an existing type. This new subclass is said to derive from the existing type, and is sometimes called a derived type.
22
Object-Oriented Concepts
Polymorphism
In Object oriented programming, polymorphism ( from the Greek meaning having multiple forms) is the characteristic of being able to assign different meaning to something in different contexts specifically, to allow an entity such as a variable, a function or an object to have more than one form. There are several different kinds of polymorphism.
23
24
Object-Oriented Concepts
Benefits of OOP:
Through inheritance, we can eliminate redundant code and extends the use of existing class. The principal of data hiding helps the programmer to build secure programs. It is easy to partition the work in a project based on objects. Object oriented systems can be easily upgraded from small to large systems. Software complexity can be easily managed.
25
C++ Fundamentals
C++, a superset of C, extends C by incorporating objectoriented features.
C++ programs differs from the C program in other ways also, including how I/O is performed and what headers are included.
26
C++ Fundamentals
A Simple C++ Program: Average of Two numbers
#include <iostream.h> int main() { float number1, number2, sum, average; cout << Enter Two numbers: ; cin >> number1; cin >> number2; sum = number1 + number2; // Sum the two numbers average = sum/2 ; cout << Average is: << average ; Return 0; }
27
C++ Fundamentals
Comments:
C++ introduces a new comment symbol ( // ). This is a single line comment. The C Style comment /*, */ are also valid.
28
C++ Fundamentals
Basic Data Types in C++:
Type Typical Size in Bytes char 1 unsigned char 1 int 2 to 4 long 4 float 4 Double 8 * -2 ^ (n-1) to (2 ^ (n-1)) - 1 void is also a data type in C++. User Defined Data Types in C++:
Structures Classes Enum
29
C++ Fundamentals
Reference variables:
Reference variables provides an alias for a previously defined variable. A reference variable is created as follows: data-type& reference-name = variable-name; Ex. float x = 50; float& y = x; // y = 50 y = 100; // x = 100, y = 100
30
C++ Fundamentals
Manipulators:
These are the operators used to format the data display. The most common manipulators are endl and setw. The endl manipulator caused a linefeed to be inserted, when used in an output statement. The setw is used to specify a common field width for all numbers and force them to be printed right justified.
31
C++ Fundamentals
Type Casts Forces an expression to be specified type by using a cast.The general form of a cast is (type-name) expression // C notation Type_name (expression) // C++ notation
32
34
35
37
38
39
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
40
41
Pointers
Pointers are variables that contains address, usually address of another variable.
Consider the declaration int i=3; i value
Location Name
6485
Address
43
Pointers
Consider int *ptr = &i;
&i gives the address of the variable i.
44
Pointers
Example
int main() { int i, *iVar; iVar = &i; *iVar = 10; cout <<*iVar = << *iVar <<i = << i ; }
45
Pointers
int main() {
int *iPtr, i=20; iPtr = &i; cout<<i before incrementing: << i << endl; *iPtr += 10; cout<<i after incrementing: << i << endl ;
}
46
0X104
H i \0
Memory Management
Provides two dynamics allocation operators:
new To allocate the memory at run time delete free memory at run time. The general form of the new operator is: type *var = new type[size] Where type is the datatype of the variable, for which you are going to allocate the memory. Var is the variable name which will hold that much of memory. Size is the amount of memory to hold a variable.
Ex. int* pInt = new int[4] pInt will hold memory to have four interger variables.
49
Memory Management
The general form of the delete operator is:
delete var This will delete memory hoded by the var. Use delete [ ] var , if you are using new type[ ] . Use delete var , if you are using new type.
50
Memory Management
Advantage of new over malloc:
1. Automatically computes the size of the data object. We need not use the operator sizeof. 2. Automatically returns the correct pointer type, so no need to use a type cast. 3. It is possible to initialize the object while creating the memory space. Ex. int* p = new int(10); 4. new and delete can be overloaded.
51
Functions
Functions are used to divide your large program into smaller parts and is the major principles of top-down, structured programming.
In C++, the main() returns a value of type int to the operating system.
A function, that have a return value should use the return statement for termination.
52
Functions
The general form to create a Function is:
ret-type function_name(argument-list) { Body of the function } ret_type specifies the type of data that the function returns. A function may return any type of data except an array. argument-list is a comma separated list of variables names and their associated types that receives the values of the arguments when the function is called.
53
Functions
54
Functions
Calling a function
A function can be called in two ways in C++: Call by value Call by reference
55
Functions
Call by Value
When an argument is passed call by value, a copy of the arguments value is made and passed to the called function i.e original variable is never passed to the function. Changes to the copy do not affect the original variables value in the caller. This prevents the accidental side affect that so greatly hinder the development of correct and reliable software system. One disadvantage of call by value is that if a large data item is being passed copying that data can take a considerable amount of execution time.
56
Functions
Example: Call by Value
int main() { int i = 5; i = mynumber(i); cout << My number is: << i << endl ; return 0; } int mynumber(int i) { i = i + 1; Return i; }
57
Functions
Call by reference
Call by reference can be done by two ways either using reference arguments or with pointer arguments.
When calling a function with arguments that should be modified, the addresses of the arguments are passed. This is normally accomplished by applying the address operator (&) to the name of the variable whose value will be modified.
58
Functions
Example : Call by Reference
int main() { int mynumber(int& i); // function declaration int i = 5; i = mynumber(i); cout << "My number is: " << i << endl ; return 0; } int mynumber(int &i) { i = i + 1; return i; }
59
Functions
Example : Through Pointers
int main() { int mynumber(int* i); // function declaration int i = 5; i = mynumber(&i); cout << "My number is: " << i << endl ; return 0; } int mynumber(int* i) { *i = *i + 1; return *i; }
60
Functions
inline functions:
To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.
Functions
inline keyword is merely a request, not a command, to the compiler. Using inline functions can reduce execution time but increase program size inline expansion may not occur in following situations Functions containing static variables Recursive functions Functions containing loop, switch, go to statements.
62
Storage Classes
A variables storage class determines the period during which that variable exists in memory. Some variable exist briefly, some are repeatedly created and destroyed and others exist for the entire execution of a program.
63
Storage Classes
Four Types of Storage Classes
1. 2. 3. 4. Auto register static extern
64
Storage Classes
Auto
A functions local variables and parameters normally are of automatic storage class.
Scope : Function in which it is declared Lifetime : Into the function only Default value : Garbage
E.g.. auto double x,y; Local variables are of automatic storage class by default, so keyword auto is rarely used.
65
Storage Classes
Register
The storage class specified register can be placed before an automatic variable declaration to suggest that the compiler maintain the variable in one of the computers high performance speed hardware register rather than in the memory.
Scope : Function in which it is declared Lifetime : Into the function only Default value: Garbage value
It is used for intensely used variables such as counters or totals can be maintained in hardware registers. E.g. register int counter = 1;
The compiler might ignore register declarations.
66
Storage Classes
Extern
Used to tell all the files about the global variables required by program. Scope: in whole the program, Exist from the point it is declared. Lifetime whole the program Default value 0 ( Zero) For variables, storage is allocated and initialized once when the program begins execution. Global variables and function names are its examples.
67
Storage Classes
File One int x,y; char ch; int main() { }
void func() {
x = 123;
File Two extern int x,y; extern char ch; int main() { }
void nextfunc() {
y = 10;
}
68
Storage Classes
Static
Static variables are permanent variables with in their own function or file. Scope: Within the function or file where declared Lifetime: Whole the program Default value: 0( Zero )
70
72
73
74
75
Recall that the private members of an object are accessible only by functions that are the member of that object. Ex. stack1.tos = 0; // Error, tos is private.
77
80
Constructor Definition:
Stack::stack() { tos = 0; cout << Stack initialized << endl; }
Destructor Definition:
Stack::~stack() { cout << Stack destroyed<< endl; }
83
84
The most common general form of a copy constructor is: classname(const classname& ob) { // body of the constructor } where ob is a reference to the object on the right side of the initialization.
85
copy constructor is also called when you pass arguments in a function or return value from a function as a call by value.
Defining a copy constructor can help you prevent problems that might occur when one object is used to initialize others.
86
88
90
91
92
} int sum(myclass x) {
return x.a + x.b ;
94
Friend functions are not a member of class. So they are called just as a plain function.
myclass ob; ob.set_ab(2,3); cout << sum(ob);
95
97
98
99
Inheritance
Inheritance is to support the concept of reusability in C++. The Mechanism of deriving a new class from an old one is called Inheritance.
The Old class is called base class( Parent Class ) and the new one is called the derived class (Child Class) .
A class can inherit properties from more than one class. A derived class with only one base class is called single inheritance and one with several base classes is called multiple inheritance.
100
Inheritance
Defining Derived Classes:
class derived-class-name : visibility-mode base-class-name { // members of the derived class. } Ex. class ABC : private XYZ
{
// members of ABC class. }
101
Inheritance
When a base class is privately inherited by a derived class, public members of the base class becomes private members of the derived class.
When a base class is publicly inherited by a derived class, public members of the base class become public members of the derived class. In both the cases, the private members are not inherited. Base class member can be overridden by defining a derived class member with the same name as that of base class member. To access base class member from a derived class, the scope resolution operator may be used.
102
Inheritance
Different forms of Inheritance
1. Single inheritance 2. Multiple inherence 3. Hierarchical inheritance 4. Multilevel inheritance
Single Inheritance
When a subclass inherits only from one base class, it is known as single inheritance.
103
Inheritance
104
Inheritance
Making a private member inheritable:
protected is used for this purpose. A member declared as protected is accessible by the member functions within its class and any class immediately derived from it. Can not be accessed by the functions outside these two classes. When a protected member is inherited in public mode, it becomes protected in the derived class too. If it is inherited in private mode, becomes private in the derived class.
105
Inheritance
106
Inheritance
107
Inheritance
Hierarchal Inheritance
When many subclasses inherit from a single base class, it is known as hierarchical inheritance.
108
Inheritance
109
Inheritance
Multiple Inheritance
When a subclass inherits from multiple base classes, it is known as multiple inheritance.
110
Inheritance
111
Inheritance
Subclass inherits properties from multiple base classes. Syntax:
class derived: visibilty base1, visibilty base2 { // }
Multiple Inheritance occurs when a class inherits from more than one parent
112
Inheritance
Example:
class M { protected: int m; public: void get_m(int x); }; class N { protected: int n; public: void get_n(int y); }; void M :: get_m(int x) { m = x; } void N :: get_n(int y) { n = y; } void P :: display() { cout << "m = " << m << endl; cout << "n = " << n << endl; cout << "m*n = " << m * n << endl; } int main() { Pp; p.get_m(10); p.get_n(20); p.display(); return 0; }
113
Inheritance
114
Inheritance
Ambiguities in Multiple Inheritance
int Avar
D
int Dvar
115
Inheritance
116
Inheritance
Virtual Base Class
To avoid ambiguity, modify class definitions as below:
class A{}; class B:virtual public A {}; class C:virtual public A {}; class D:public B, public C {};
117
Inheritance
Constructors in Derived Classes:
If a base class has a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors. Base class constructor is executed first and then derived class constructor. In case of multiple inheritance, the base classes are constructed in order in which they are declared in the derived class declaration.
118
Inheritance
The general form of defining a derived constructor is:
derived-constructor(arglist1,arglist2, , arglistN, arglistD) : base1(arglist1), base2(arglist2), . . . baseN(arglistN) { Body of the derived class }
119
Inheritance
destructors are executed in the reverse order of the Constructor.
120
class alpha { int x; public: alpha(int i) { x=i; cout << "alpha initialized" << endl; } void show_x() { cout << "x = " << x << endl; } }; class beta { int y; public: beta(int j) { y = j; cout << "beta initialized " << endl; } void show_y() { cout << "y = " << y << endl; } };
class gamma : public alpha, public beta { int m, n ; public: gamma(int a, int b, int c, int d) : alpha(a), beta(b) { m = c; n = d; cout << "gamma initilized" << endl; } void show_mn() { cout << "m = " << m << endl << "n = " << n << endl; } }; int main() { gamma g(5,10,15,20); g.show_x(); g.show_y(); g.show_mn(); return 0; }
121
Inheritance
Nesting of Classes:
Another way of inheriting properties of one class into another. This type of relationshio is called containership or nesting. Ex. class alpha { }; class beta { }; class gamma { alpha a; beta b; };
122
123
Polymorphism
Polymorphism means many forms. Same message ( member function) sent to different objects would be processed in different ways. Two type of Polymorphism:
Compile Time Polymorphism Function Overloading Operator Overloading
124
Polymorphism
Function Overloading
C++ enables several functions of the same name to be defined as long as these functions have different sets of parameters. This capability is called function overloading. When an overloaded function is called the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call.
125
Polymorphism
Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types. Creating overloaded functions with identical parameter lists and different return types is a syntax error.
126
Polymorphism
Overloaded functions are distinguished by their signaturesa signature is a combination of a functions name and its parameter types.
127
Polymorphism
Example
int square (int x) {return x * x; } Double square (double y) {return y * y; } int main() { cout<<Square of int 7 is <<square(7) <<\n Square of double 7.5 is <<square(7.5)<<endl; return 0; }
128
Polymorphism
Operator Overloading
Operator overloading contributes to C++s extensibility, one of the languages most appealing attributes. When an operator is overloaded, none of its original meaning lost. You can overload the operators by creating operator functions. An operator function is created using the keyword operator.
Operator functions can be either members or nonmembers ( friends ) of a class. Basic difference between them is that a friend function will have only one argument for unary operator and two for binary operator, while a member function has no argument for unary operator and only one for binary operators.
129
Polymorphism
Defining Operator Overloading:
ret-type class-name :: operator # (arg-list) { Function body } # is an place holder, substitute your operator in place of #. Ex. vector operator + ( vector ); // vector addition friend vector operator + ( vector , vector ); vector operator (); // unary minus friend vector operator (vector );
130
Polymorphism
Invoking overloaded operator functions:
For Unary Operator: op x or x op ( where op = operator , x = object )
131
Polymorphism
Examples: Through Member Function
String& operator + ( const String& s) {
Polymorphism
Examples: Through Friend Function
friend String& operator + ( String s1, String s2) { char* temp; temp = new char[strlen(s1.str) + strlen(s2.str) + 1]; temp = strcat(s1.str ,s2.str ); return String(temp); } In Main(): String s1("CSC"); String s2(" India"); s1 = s1 + s2; // will print CSC India
133
Polymorphism
We can overload all the C++ operator except the following:
Scope Resolution Operator ( :: ) Size Operator ( sizeof() ) Conditional Operator ( ? : ) Class Member Access Operator (., .*)
134
Polymorphism
Virtual Functions:
Virtual functions are member functions, that is declared in base class and redifined by a derived class. The redefinition of a virtual function in a derived class is usually called overriding. To create a virtual function, precede the function declaration by keyword virtual. Virtual functions are used to achieve the Run time polymorphism.
135
Polymorphism
A base class pointer can be used to point to an object of any class derived from the base.
When a base pointer points to a derived object that contains a virtual function, C++ determines which version of that function is called function is called based upon the type of object pointed to by the pointer.
136
Polymorphism
class shape { public: virtual void display() { cout << "In the shape class " << endl;} }; class circle : public shape { public: void display() };
class triangle : public shape { public: void display() { cout << "In the triangle class" << endl; } };
int main(int argc, char* argv[]) { shape* pSh = new shape; pSh->display(); pSh = new circle; pSh->display(); pSh = new triangle; pSh->display(); return 0;
137
Polymorphism
Pure Virtual Functions:
This is a function that is declared in the base class that has no definition relative to the base class. Pure virtual function are declared like below: virtual void display() = 0; Each derived class to either define the function or redeclare it as a pure virtual functions. Abstract Class: A class containing at least one pure virtual function can not be used to declare any objects of its own.
138
139
Exception Handling
Exception Handling allows you to manage run time errors.
Exception Handling is built upon three keywords:
try catch throw
Program statements that you want to monitor for exceptions are contained in a try block. If an exception occurs within the try block, it is thrown using the throw. The exception is caught using the catch and processes.
140
Exception Handling
The General form of try and catch is:
try { // statements } catch(type1 arg) { // catch block } catch(type2 arg) { } . . Catch(typeN arg) { }
141
Exception Handling
When an exception is thrown, it is caught by its corresponding catch statement. Which catch statement is executed is determined by the data type of the exception.
throw statement:
throw exception throw generates the exception specified by exception. If you throw an exception for which there is no applicable catch statement,an abnormal program termination may occur.
142
Exception Handling
Using Multiple catch Statement Example:
void test(int i) { try { if(i) throw i; else throw "value is zero"; } catch(int num) { cout << "Caught exception number: " << num << endl; } catch(char* str) { cout << "Caught exception string: " << str << endl; } } int main() { test(1); test(2); test(0); test(3);
// Caught exception number: 1 // Caught exception number: 2 // Caught exception string: value is zero // Caught exception number: 3
143
Exception Handling
Catching All Exception:
Use this form of catch catch() { // stmt } Use of this form is write it as the last catch of a cluster of catches.
144
Templates
Templates are used to create generic functions and classes. You can use one function or class with several different types of data without having to explicitly recode specific versions for each data type. These cab be created with template keyword.
145
Templates
Generic Functions:
By creating a generic function, you can define the nature of the algorithm, independent of any data. The general form of a template function definition is: template<class T> ret-type func-name(parameter list) { body of the function }
146
Templates
Example:
template<class T> T summation(T a, T b) { return a + b; } int main() { cout << "Summation of two integer is: " << summation(2,3) << endl; cout << "Summation of two float is: " << summation(2.2,3.3) << endl; return 0; }
147
Templates
Generic Classes:
Generic classes are useful when a class uses logic that can be generalized. Ex. The same algorithm that will maintain a queue of integers will also work for a queue of characters. The compiler will automatically generate the correct type of object, based upon the type you specify when the object is created.
148
Templates
The general form of the class decaration is:
Template<class T> Class class-name { . . . };
149
Templates
template<class T> class Stack { private: T stck[10]; int tos; public: Stack() { tos = 0 ;}; void push(T num); T pop(); };
template<class T> void Stack<T> :: push(T num) { if(tos == 10) { cout << "Stack is full" << endl; return; } else { stck[tos] = num; tos++; } }
template<class T> T Stack<T> :: pop() { if(tos == 0) { cout << "Stack is empty" << endl; return 0; } else { tos--; return stck[tos]; } }
int main() { Stack<int> oInt>; oInt.push(10); oInt.push(20); oInt.pop(); oInt.pop(); Stack<char> oChr; oChr.push(a); oChr.push(c); oChr.pop(); oChr.pop();
// stack of integer
return 0; }
150