IT3072 : Object Oriented Programming Credit:4rahuldiwate.com/Download/OOP-Complete-Section1.pdf ·...

Post on 16-Jul-2020

19 views 0 download

Transcript of IT3072 : Object Oriented Programming Credit:4rahuldiwate.com/Download/OOP-Complete-Section1.pdf ·...

IT3072 : Object Oriented Programming

Credit:4

www.rahuldiwate.com

Fundamentals of C++,Inheritance and Polymorphism

Section-1

www.rahuldiwate.com

Prof. R. B. DiwateAssistant Professor ,IT&MCA, VIT, Pune

Programming paradigms: Imperative/Procedural, Object Oriented, Functional Programming,

Programming paradigms are a way to classify programming languagesbased on their features. Languages can be classified into multiple paradigms.

Common programming paradigms include: imperative in which the programmer instructs the machine how to change its

state, procedural which groups instructions into procedures, object-oriented which groups instructions together with the part of the state

they operate on, declarative in which the programmer merely declares properties of the desired

result, but not how to compute it functional in which the desired result is declared as the value of a series of

function applications, logic in which the desired result is declared as the answer to a question about

a system of facts and rules, mathematical in which the desired result is declared as the solution of an

optimization problem3

Programming paradigms: Imperative/Procedural, Object Oriented, Functional Programming,

Procedural Programming (functions)Modular Programming (namespaces)Object Oriented Programming (classes)Generic Programming (templates)

4 www.rahuldiwate.com (Prof. R.B.Diwate)

Need of Object-Oriented Programming (OOP)

5 www.rahuldiwate.com (Prof. R.B.Diwate)

6 www.rahuldiwate.com (Prof. R.B.Diwate)

7 www.rahuldiwate.com (Prof. R.B.Diwate)

Benefits of OOP Through inheritance, we can eliminate redundant code extend the use of existing • Classes. • We can build programs from the standard working modules that communicate with one

another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity.

• The principle of data hiding helps the programmer to build secure program that can not be invaded by code in other parts of a programs.

• It is possible to have multiple instances of an object to co-exist without any interference.

• It is possible to map object in the problem domain to those in the program. • It is easy to partition the work in a project based on objects. • The data-centered design approach enables us to capture more detail of a model can

implemental form. • Object-oriented system can be easily upgraded from small to large system. • Message passing techniques for communication between objects makes to interface

descriptions with external systems much simpler. • Software complexity can be easily managed. 8

Application of OOP Real-time system Simulation and modeling Object-oriented data bases Hypertext, Hypermedia, and expertext AI and expert systems Neural networks and parallel programming Decision support and office automation systems CIM/CAM/CAD systems

9 www.rahuldiwate.com (Prof. R.B.Diwate)

C++ Programming: Basics, Data Types, Structures,

10 www.rahuldiwate.com (Prof. R.B.Diwate)

11 www.rahuldiwate.com (Prof. R.B.Diwate)

12 www.rahuldiwate.com (Prof. R.B.Diwate)

13 www.rahuldiwate.com (Prof. R.B.Diwate)

Class, Object, class and data abstraction Basic Concept of OOP Class Objects Data Abstraction & Encapsulation Inheritance Polymorphism Dynamic Binding Message Passing

14 www.rahuldiwate.com (Prof. R.B.Diwate)

15 www.rahuldiwate.com (Prof. R.B.Diwate)

Objects ,Class

Objects ate run-time entities in object oriented programming,

Ex. Fruit Mango; Will create and object Mango belonging to class fruit.

16 www.rahuldiwate.com (Prof. R.B.Diwate)

Data Abstraction

17 www.rahuldiwate.com (Prof. R.B.Diwate)

Data Abstraction: Example

18 www.rahuldiwate.com (Prof. R.B.Diwate)

Types of Inheritance Single Inheritance Multiple Inheritance Multilevel Inheritance Hierarchical Inheritance Hybrid Inheritance

19 www.rahuldiwate.com (Prof. R.B.Diwate)

Single Inheritance: In Single Inheritance one class extends another class (one

class only).

In above diagram, Class B extends only Class A. Class A is a super class and Class B is a Sub-class.

20 www.rahuldiwate.com (Prof. R.B.Diwate)

Multiple Inheritance: In Multiple Inheritance, one class extending more than

one class. Java does not support multiple inheritance.

As per above diagram, Class C extends Class A and Class B both.

21 www.rahuldiwate.com (Prof. R.B.Diwate)

Multilevel Inheritance: In Multilevel Inheritance, one class can inherit from a

derived class. Hence, the derived class becomes the baseclass for the new class.

As per shown in diagram Class C is subclass of B and B is a of subclass Class A.

22 www.rahuldiwate.com (Prof. R.B.Diwate)

Hierarchical Inheritance: In Hierarchical Inheritance, one class is inherited by many

sub classes.

As per above example, Class B, C, and D inherit the same class A.

23 www.rahuldiwate.com (Prof. R.B.Diwate)

Hybrid Inheritance: Hybrid inheritance is a combination of Single and Multiple inheritance.

As per above example, all the public and protected members of Class A are inherited into Class D, first via Class B and secondly via Class C.

24 www.rahuldiwate.com (Prof. R.B.Diwate)

Syntax

class derived-class extends base-class { //methods and fields }

25 www.rahuldiwate.com (Prof. R.B.Diwate)

26 www.rahuldiwate.com (Prof. R.B.Diwate)

Syntax:Syntax:class subclass_name : access_mode base_class_name{ //body of subclass};

Here, subclass_name is the name of the sub class, access_mode is themode in which you want to inherit this sub class for example: public,private etc. and base_class_name is the name of the base class fromwhich you want to inherit the sub class.

Note: A derived class doesn’t inherit access to private data members.However, it does inherit a full parent object, which contains any privatemembers which that class declares.

27 www.rahuldiwate.com (Prof. R.B.Diwate)

#include <bits/stdc++.h>

using namespace std;

//Base class

class Parent

{ public:

int id_p;

};

// Sub class inheriting from Base Class(Parent)

class Child : public Parent

{

public:

int id_c;

};

//main function

int main()

{

Child obj1; // An object of class child has all data members and member functions of class parent

obj1.id_c = 7;

obj1.id_p = 91;

cout << "Child id is " << obj1.id_c << endl;

cout << "Parent id is " << obj1.id_p << endl;

return 0;

}

Output:

Child id is 7 Parent id is 91 28 www.rahuldiwate.com (Prof. R.B.Diwate)

Modes of Inheritance Public mode: If we derive a sub class from a public

base class. Then the public member of the base classwill become public in the derived class and protectedmembers of the base class will become protected inderived class.

Protected mode: If we derive a sub class from aProtected base class. Then both public member andprotected members of the base class will becomeprotected in derived class.

Private mode: If we derive a sub class from a Privatebase class. Then both public member and protectedmembers of the base class will become Private inderived class.

29 www.rahuldiwate.com (Prof. R.B.Diwate)

Polymorphism The word polymorphism means having many forms. In simple

words, we can define polymorphism as the ability of a messageto be displayed in more than one form.Real life example of polymorphism, a person at the same timecan have different characteristic. Like a man at the same time isa father, a husband, an employee. So the same person possesdifferent behavior in different situations.

This is called polymorphism.

Polymorphism is considered as one of the important featuresof Object Oriented Programming.

In C++ polymorphism is mainly divided into two types: Compile time Polymorphism Runtime Polymorphism

30 www.rahuldiwate.com (Prof. R.B.Diwate)

class scope and accessing class members A class’s data members and member functions belong to that class’s scope. Nonmember functions are defined at global namespace scope. Within a class’s scope, class members are immediately accessible by all of that class’s

member functions and can be referenced by name. Outside a class’s scope, class members are referenced through one of the handles on

an object: an object name, a reference to an object, or a pointer to an object. Member functions of a class can be overloaded only by other member functions of

that class. To overload a member function, provide in the class definition a prototype for each

version of the overloaded function, and provide a separate definition for each versionof the function.

Variables declared in a member function have local scope and are known only to thatfunction.

The dot member selection operator (.) is preceded by an object’s name or by areference to an object to access the object’s public members.

Constructors with Default Arguments Like other functions, constructors can specify default arguments.31

Operator Overloading: Concept, Operator overloading, Overloading Unary Operators, Binary Operators. Operator overloading is a compile-time polymorphism in which the

operator is overloaded to provide the special meaning to the user-defined data type. ... For example, C++ provides the ability to add thevariables of the user-defined data type that is applied to the built-in datatypes.

32 www.rahuldiwate.com (Prof. R.B.Diwate)

Unary Operators Unary operator acts on one operand only. In case

overloaded operator function is a class member function,then it will act on the object with which it is called and use itas operand. Hence we need not to pass any extra argument inunary operator function if its class member function.

Type of operator ++ (Increment Operator) — (Decrement operator) – (Unary Minus operator) ! (NOT Operator)

33 www.rahuldiwate.com (Prof. R.B.Diwate)

#include<iostream.h> #include<conio.h> class complex { int a, b, c; public: complex() { } void getvalue() { cout << "Enter the Two Numbers:"; cin >> a>>b; } void operator++() { a = ++a; b = ++b; } void operator--() { a = --a; b = --b; } void display() { cout << a << "+\t" << b << "i" << endl; } };

void main() {clrscr(); complex obj; obj.getvalue(); obj++; cout << "Increment Complex Number\n"; obj.display(); obj--; cout << "Decrement Complex Number\n"; obj.display(); getch(); }

Output:Enter the two numbers: 3 6 Increment Complex Number 4 + 7i Decrement Complex Number 3 + 6i

34 www.rahuldiwate.com (Prof. R.B.Diwate)

Binary Operators. C++ provides a special function to change the current functionality of

some operators within its class which is often called as operatoroverloading. Operator Overloading is the method by which we canchange the function of some specific operators to do some differenttask.

The binary operators take two arguments and following are theexamples of Binary operators. You use binary operators very frequentlylike addition (+) operator, subtraction (-) operator and division (/)operator.

35 www.rahuldiwate.com (Prof. R.B.Diwate)

36 www.rahuldiwate.com (Prof. R.B.Diwate)

Operator Overloading: C++ also provide option to overload operators. For

example, we can make the operator (‘+’) for string classto concatenate two strings. We know that this is theaddition operator whose task is to add two operands. Soa single operator ‘+’ when placed between integeroperands , adds them and when placed between stringoperands, concatenates them.

37 www.rahuldiwate.com (Prof. R.B.Diwate)

// Operator Overloading

#include<iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i =0) {real = r; imag = i;} // This is automatically called when '+' is used with between two Complex objects

Complex operator + (Complex const &obj) {

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

} void print() { cout << real << " + i" << imag << endl; }

}; int main()

{

Complex c1(10, 5), c2(2, 4);

Complex c3 = c1 + c2; // An example call to "operator+"

c3.print();

}

Output:

12 + i9 38 www.rahuldiwate.com (Prof. R.B.Diwate)

Overloading a method (or function) in C++ is the ability forfunctions of the same name to be defined as long as these methodshave different signatures (different set of parameters). Methodoverriding is the ability of the inherited class rewriting the virtualmethod of the base class.

a) In overloading, there is a relationship between methods availablein the same class whereas in overriding, there a is relationshipbetween a superclass method and subclass method.

(b) Overloading does not block inheritance from the superclasswhereas overriding blocks inheritance from the superclass.

(c) In overloading, separate methods share the same name whereasin overriding, subclass method replaces the superclass.

(d) Overloading must have different method signatures whereasoverriding must have same signature.

39 www.rahuldiwate.com (Prof. R.B.Diwate)

Runtime Polymorphism This type of polymorphism is achieved by Function

Overriding. Function overriding on the other handoccurs when a derived class has a definition for one ofthe member functions of the base class. That basefunction is said to be overridden.

If derived class defines same function as defined inits base class, it is known as function overriding inC++.

40 www.rahuldiwate.com (Prof. R.B.Diwate)

Note: In function overriding, the function in parent class is called the overridden function and function in child class is called overriding function.

41 www.rahuldiwate.com (Prof. R.B.Diwate)

// C++ program for function overriding

#include <iostream.h>

using namespace std;

class base {

public:

virtual void print ()

{ cout<< "print base class" <<endl; }

void show ()

{ cout<< "show base class" <<endl; }

}; class derived:public base

{

public:

void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly

{ cout<< "print derived class" <<endl; }

void show ()

{ cout<< "show derived class" <<endl; }

};

Examples

42 www.rahuldiwate.com (Prof. R.B.Diwate)

//main function int main() { base *bptr; derived d; bptr = &d;

//virtual function, binded at runtime (Runtime polymorphism) bptr->print();

// Non-virtual function, binded at compile time bptr->show();

return 0; }

Output: print derived class show base class 43 www.rahuldiwate.com (Prof. R.B.Diwate)

Dynamic binding Dynamic binding also called dynamic dispatch is the

process of linking procedure call to a specific sequence ofcode (method) at run-time. It means that the code to beexecuted for a specific procedure call is not known untilrun-time. Dynamic binding is also known as late binding orrun-time binding.

Dynamic binding is an object oriented programmingconcept and it is related with polymorphism andinheritance.

44 www.rahuldiwate.com (Prof. R.B.Diwate)

Dynamic binding definition Dynamic binding(dispatch)means that a block of code executed with reference to aprocedure(method) call is determined at run time.

Dynamic dispatch is generally used when multiple classescontain different implementations of the same method. Itprovides a mechanism for selecting the function to beexecuted from various function alternatives at the run-time. In C++, virtual functions are used to implementdynamic binding.

45 www.rahuldiwate.com (Prof. R.B.Diwate)

Example

46 www.rahuldiwate.com (Prof. R.B.Diwate)

Message Passing Message Passing is nothing but sending and receiving of information by

the objects same as people exchange information. So this helps in buildingsystems that simulate real life. Following are the basic steps in messagepassing.

1. Creating classes that define objects and its behavior.

2. Creating objects from class definitions

3. Establishing communication among objects

In OOPs, Message Passing involves specifying the name of objects, the nameof the function, and the information to be sent.

Message passing definition Message passing is a form of communicationbetween objects, processes or other resources used in object-orientedprogramming, inter-process communication and parallel computing.

47 www.rahuldiwate.com (Prof. R.B.Diwate)

Message passing is a type of communication between processes or objectsin computer science. In this model, processes or objects can send andreceive messages (signals, functions, complex data structures, or datapackets) to other processes or objects.

48 www.rahuldiwate.com (Prof. R.B.Diwate)

Separating interface from implementation, controlling access to members

Data hiding is one of the important features of Object Oriented Programmingwhich allows preventing the functions of a program to access directly the internalrepresentation of a class type. The access restriction to the class members isspecified by the labeled public, private, and protected sections within the classbody.The keywords public, private, and protected are called access specifiers.

A class can have multiple public, protected, or private labeled sections. Each sectionremains in effect until either another section label or the closing right brace of theclass body is seen.The default access for members and classes is private.

49 www.rahuldiwate.com (Prof. R.B.Diwate)

Public Access Modifier in C++ Public, means all the class members declared under

public will be available to everyone. The data membersand member functions declared public can be accessed byother classes too. Hence there are chances that theymight change them. So the key members must not bedeclared public.

50 www.rahuldiwate.com (Prof. R.B.Diwate)

Private Access Modifier in C++ Private keyword, means that no one can access the class

members declared private, outside that class. If someonetries to access the private members of a class, they willget a compile time error. By default class variables andmember functions are private.

51 www.rahuldiwate.com (Prof. R.B.Diwate)

Protected Access Modifier in C++ Protected, is the last access specifier, and it is similar to

private, it makes class member inaccessible outside theclass. But they can be accessed by any subclass of thatclass. (If class A is inherited by class B, then class B issubclass of class A.

52 www.rahuldiwate.com (Prof. R.B.Diwate)

Functions: Function prototype A function prototype is a declaration of the function that tells the program about

the type of the value returned by the function and the

number and type of arguments. A function prototype describes the function interface to the compiler by giving

details such as the number and type of arguments and the type of return values. The prototype declaration looks just like a function definition except that it has

no body i.e., its code is missing. This is the time you knew the differencebetween a declaration and a definition.

A declaration introduces a (function) name to the program whereas a definitionis a declaration that also tells the program what the function is doing and how itis doing.

53 www.rahuldiwate.com (Prof. R.B.Diwate)

Example1. int absval(int a);

int gcd(int n1, int n2);

2. return type name of the function argument list

Therefore, you can say that a function prototype has the following parts :

Here, int sum(int n1, int n2); 1. return type - int2. name of the function - sum3. argument list - (int n1, int n2)

Since every function prototype is followed by a semicolon, so at last there will be ; as in the above function prototype.

A function declaration can skip the argument names but a function definition, can not

54 www.rahuldiwate.com (Prof. R.B.Diwate)

Use of Void void data type that it specifies an empty set of values and it is used as

the return type for functions that do not return a value. Thus, afunction that does not return a value is declared as follows:

void function_name(parameter list);

By declaring a function's return type void, one makes sure that the functioncannot be used in an assignment statement.

55 www.rahuldiwate.com (Prof. R.B.Diwate)

ConstructorsA constructor is a special type of member function that initializes an objectautomatically when it is created.Compiler identifies a given member function is a constructor by its name and thereturn type.Constructor has the same name as that of the class and it does not have any returntype

Types of Constructor

Default Constructor.Parametrized Constructor.Copy Constructor.Static Constructor.Private Constructor.

56 www.rahuldiwate.com (Prof. R.B.Diwate)

Syntax

57 www.rahuldiwate.com (Prof. R.B.Diwate)

Why Constructor is important? The main purpose of the class constructor in C++

programming is to construct an object of the class. In other word, it is used to initialize all class data

members.

58 www.rahuldiwate.com (Prof. R.B.Diwate)

For example,in below class,constructor Car () isinitializing data memberswith default values.And, when we create theobject of a class, thisconstructor will always becalled.

59

60 www.rahuldiwate.com (Prof. R.B.Diwate)

Copy Constructor What is a copy constructor?

A copy constructor is a member function which initializes an object using another object of the same class.

A copy constructor has the following general function prototype:

Syntax ClassName (const ClassName &old_obj);

61 www.rahuldiwate.com (Prof. R.B.Diwate)

Copy Constructor A copy constructor is the constructor that C++ uses to

make copies of objects. It carries the name X::X(const X&), where X is the name

of the class. That is, it’s the constructor of class X, which takes as its

argument a reference to an object of class X.

62 www.rahuldiwate.com (Prof. R.B.Diwate)

63 www.rahuldiwate.com (Prof. R.B.Diwate)

When is copy constructor called? In C++, a Copy Constructor may be called in following cases: 1.When an object of the class is returned by value. 2. When an object of the class is passed (to a function) by

value as an argument. 3. When an object is constructed based on another object of

the same class. 4.When the compiler generates a temporary object.

64 www.rahuldiwate.com (Prof. R.B.Diwate)

Shallow copy The default copy constructor can only produce the shallow copy.

A Shallow copy is defined as the process of creating the copy of an object by copying data of all the member variables as it is.

65 www.rahuldiwate.com (Prof. R.B.Diwate)

class Demo { int a; int b; int *p; public: Demo() { p=new int; } void setdata(int x,int y,int z) { a=x; b=y; *p=z; } void showdata() { std::cout << "value of a is : " <<a<< std::endl; std::cout << "value of b is : " <<b<< std::endl; std::cout << "value of *p is : " <<*p<< std::endl; } }; int main() { Demo d1; d1.setdata(4,5,7); Demo d2 = d1; d2.showdata(); return 0; }

Output:value of a is : 4value of b is : 5 value of *p is : 7

66 www.rahuldiwate.com (Prof. R.B.Diwate)

Deep copyDeep copy dynamically allocates the memory for the copy and then copies the actualvalue, both the source and copy have distinct memory locations. In this way, both thesource and copy are distinct and will not share the same memory location. Deepcopy requires us to write the user-defined constructor.

67 www.rahuldiwate.com (Prof. R.B.Diwate)

class Demo {public: int a; int b; int *p;Demo(){ p=new int; }Demo(Demo &d){ a = d.a; b = d.b; p = new int; *p = *(d.p); }

void setdata(int x,int y,int z){ a=x; b=y; *p=z; }void showdata(){ std::cout << "value of a is : " <<a<< std::endl;

std::cout << "value of b is : " <<b<< std::endl;std::cout << "value of *p is : " <<*p<< std::endl;

} };int main() {Demo d1;d1.setdata(4,5,7);Demo d2 = d1;d2.showdata();return 0; }

Outputvalue of a is : 4 value of b is : 5 value of *p is : 7

68

Destructors C++ destructor is a special member function that is executed

automatically when an object is destroyed that has been created by theconstructor. C++ destructors are used to de-allocate the memory thathas been allocated for the object by the constructor.

Syntax ~class_name() { }; //syntax of destructor

/*...syntax of destructor....*/class class_name{ public: class_name(); //constructor. ~class_name(); //destructor.}

69www.rahuldiwate.com (Prof. R.B.Diwate)

Objects and Memory requirements We can define class members static using static keyword.

When we declare a member of a class as static it means nomatter how many objects of the class are created, there is onlyone copy of the static member.

Declare the global data which should be updated while theprogram lives in memory

A static member is shared by all objects of the class. All staticdata is initialized to zero when the first object is created, if noother initialization is present.

We can't put it in the class definition but it can be initializedoutside the class as done in the following example by redeclaringthe static variable, using the scope resolution operator :: toidentify which class it belongs to.

70 www.rahuldiwate.com (Prof. R.B.Diwate)

Declare the global data which should be updated while the program lives in memory

71

Static Function Members By declaring a function member as static, you make it

independent of any particular object of the class. Astatic member function can be called even if no objectsof the class exist and the static functions areaccessed using only the class name and the scoperesolution operator :: .

A static member function can only access static datamember, other static member functions and any otherfunctions from outside the class. Static memberfunctions have a class scope and they do not haveaccess to the this pointer of the class. You could use astatic member function to determine whether someobjects of the class have been created or not.

72 www.rahuldiwate.com (Prof. R.B.Diwate)

73

Inline function If a function is inline, the compiler places a copy of the

code of that function at each point where the function iscalled at compile time.

Any change to an inline function could require all clients ofthe function to be recompiled because compiler wouldneed to replace all the code once again otherwise it willcontinue with old functionality.

To inline a function, place the keyword inline before thefunction name and define the function before any callsare made to the function. The compiler can ignore the inlinequalifier in case defined function is more than a line.

A function definition in a class definition is an inlinefunction definition, even without the use of the inlinespecifier.

74 www.rahuldiwate.com (Prof. R.B.Diwate)

75 www.rahuldiwate.com (Prof. R.B.Diwate)

76 www.rahuldiwate.com (Prof. R.B.Diwate)

Friend Functions One of the important concepts of OOP is data hiding, i.e., a nonmember

function cannot access an object's private or protected data. But, sometimes this restriction may force programmer to write long and

complex codes. So, there is mechanism built in C++ programming to accessprivate or protected data from non-member functions.

This is done using a friend function or/and a friend class. It access to the class's private and protected members.

Declaration of friend function in C++ class class_name { ... .. ... friend return_type function_name(arguments); ... .. ... }

77 www.rahuldiwate.com (Prof. R.B.Diwate)

Friend FunctionsA friend function is not in the scope of the class, in which it

has been declared as friend.

It cannot be called using the object of that class. It can be invoked like a normal function without any object. Unlike member functions, it cannot use the member names

directly. It can be declared in public or private part without affecting

its meaning. Usually, it has objects as arguments.

78 www.rahuldiwate.com (Prof. R.B.Diwate)

class Number { private: int a;

public: void getNum(int x); //declaration of friend function friend void printNum(Number NUM); }; //class member function definitions void Number::getNum(int x) { a=x; } //friend function definition, no need of class name with (::) void printNum(Number NUM) { cout << "Value of a (private data member of class Number): " << NUM.a; } int main() { Number nObj; //Object declaration n Obj.getNum(1000); printNum(nObj); return 0; }

Output: Value of a (private data member of class Number): 1000

79 www.rahuldiwate.com (Prof. R.B.Diwate)

Inheritance: Base Class and derived Class, protected members

80

Defining Derived Class

81 www.rahuldiwate.com (Prof. R.B.Diwate)

Example

82 www.rahuldiwate.com (Prof. R.B.Diwate)

83 www.rahuldiwate.com (Prof. R.B.Diwate)

Single Inheritance class A // base class

{

..........

};

class B : acess_specifier A // derived class

{

...........

} ;

84 www.rahuldiwate.com (Prof. R.B.Diwate)

#include <iostream> using namespace std; class base //single base class { public: int x; void getdata() { cout << "Enter the value of x = "; cin >> x; } }; class derive : public base //single derived class { private: int y; public: void readdata() { cout << "Enter the value of y = "; cin >> y; } void product() { cout << "Product = " << x * y; } };

int main() { derive a; //object of derived class a.getdata(); a.readdata();a.product(); return 0; }

OutputEnter the value of x = 3 Enter the value of y = 4 Product = 12

85 www.rahuldiwate.com (Prof. R.B.Diwate)

Multiple Inheritance class A

{ .......... };

class B

{ ........... } ;

class C : acess_specifier A, access_specifier A // derived class from A and B

{ ........... } ;

86 www.rahuldiwate.com (Prof. R.B.Diwate)

class A { public: int x; void getx() { cout << "enter value of x: "; cin >> x; } }; class B { public: int y; void gety() { cout << "enter value of y: "; cin >> y; } };

class C : public A, public B//C is derived from class A and class B { public: void sum(){ cout << "Sum = " << x + y; } }; int main(){ C obj1; //object of derived class C obj1.getx(); obj1.gety(); obj1.sum(); return 0; } Output

enter value of x: 5 enter value of y: 4 Sum = 9

87 www.rahuldiwate.com (Prof. R.B.Diwate)

Multilevel Inheritance class A // base class { ........... };

class B : acess_specifier A // derived class

{ ........... } ;

class C : access_specifier B // derived from derived class B { ........... } ;

88 www.rahuldiwate.com (Prof. R.B.Diwate)

class base //single base class

{ public: int x;

void getdata()

{

cout << "Enter value of x= ";

cin >> x;

} };

class derive1 : public base

// derived class from base class

{

public: int y;

void readdata()

{

cout << "\nEnter value of y= ";

cin >> y;

} };

class derive2 : public derive1 // derived from class derive1{ private: int z; public: void indata(){ cout << "\nEnter value of z= "; cin >> z;} void product() { cout << "\nProduct= " << x * y * z;} }; int main(){ derive2 a; //object of derived class a.getdata();a.readdata(); a.indata(); a.product(); return 0;}

OutputEnter value of x= 2 Enter value of y= 3 Enter value of z= 3 Product= 1889

Hierarchical Inheritance class A // base class { .............. }; class B : access_specifier A // derived class from A { ........... } ; class C : access_specifier A // derived class from A { ........... } ; class D : access_specifier A // derived class from A { ........... } ;

90 www.rahuldiwate.com (Prof. R.B.Diwate)

class A //single base class{ public: int x, y; void getdata() { cout << "\nEnter value of x and y:\n"; cin >> x >> y; } }; class B : public A //B is derived from class base {public: void product(){cout << "\nProduct= " << x * y; } }; class C : public A //C is also derived from class base{ public: void sum() { cout << "\nSum= " << x + y; } };

int main() { B obj1; //object of derived class B C obj2; //object of derived class C obj1.getdata(); obj1.product(); obj2.getdata();obj2.sum(); return 0;}

OutputEnter value of x and y: 2 3 Product= 6 Enter value of x and y: 2 3 Sum= 591

Hybrid Inheritance

class A { ......... }; class B : public A { .......... } ; class C { ........... }; class D : public B, public C { ........... };

92 www.rahuldiwate.com (Prof. R.B.Diwate)

class A { public: int x; }; class B : public A{ public: B() //constructor to initialize x in base class A { x = 10; } }; class C { public: int y;C() //constructor to initialize y { y = 4;} };

class D : public B, public C //D is derived from class B and class C{ public: void sum(){ cout << "Sum= " << x + y;} };int main() { D obj1; //object of derived class D obj1.sum(); return 0;}

OutputSum= 14

93 www.rahuldiwate.com (Prof. R.B.Diwate)

Constructor and destructor in Derived Class

94

Overriding Member Functions Is a feature that allows us to have a same function in child class which is

already present in the parent class. A child class inherits the data members and member functions of

parent class, but when you want to override a functionality in the childclass then you can use function overriding.

It is like creating a new version of an old function, in the child class.

95

Output:Function of Child Class

when we make the call to function (involved in overriding), the child class function (overriding function) gets called

96www.rahuldiwate.com (Prof. R.B.Diwate)

What if you want to call theoverridden function by using theobject of child class.We can do that by creating thechild class object in such a waythat the reference of parent classpoints to it

Output:Function of Parent Class

97 www.rahuldiwate.com (Prof. R.B.Diwate)

Ambiguity in Multiple Inheritance Function with a same name appears more than one base

class.

98 www.rahuldiwate.com (Prof. R.B.Diwate)

99www.rahuldiwate.com (Prof. R.B.Diwate)

100 www.rahuldiwate.com (Prof. R.B.Diwate)

Constructor and destructor in Derived Class

101

Overriding Member Functions Is a feature that allows us to have a same function in child class which is

already present in the parent class. A child class inherits the data members and member functions of parent

class, but when you want to override a functionality in the child classthen you can use function overriding.

It is like creating a new version of an old function, in the child class.

102

Output:Function of Child Class

when we make the call to function (involved in overriding), the child class function (overriding function) gets called

103 www.rahuldiwate.com (Prof. R.B.Diwate)

What if you want to call theoverridden function by using theobject of child class.We can do that by creating thechild class object in such a waythat the reference of parent classpoints to it

Output:Function of Parent Class

104www.rahuldiwate.com (Prof. R.B.Diwate)

Ambiguity in Multiple Inheritance Function with a same name appears more than one base

class.

105 www.rahuldiwate.com (Prof. R.B.Diwate)

106 www.rahuldiwate.com (Prof. R.B.Diwate)

107 www.rahuldiwate.com (Prof. R.B.Diwate)

Polymorphism: Concept, Types of polymorphism

The word polymorphism means having many forms.Typically, polymorphism occurs when there is a hierarchyof classes and they are related by inheritance.

C++ polymorphism means that a call to a memberfunction will cause a different function to be executeddepending on the type of object that invokes the function.

Two types of polymorphism:1) Compile time Polymorphism – This is also known as static (or early) binding.2) Runtime Polymorphism – This is also known as dynamic (or late) binding.

108 www.rahuldiwate.com (Prof. R.B.Diwate)

Compile time Polymorphismwe have two functions withsame name but differentnumber of arguments.Based on how manyparameters we pass duringfunction call determineswhich function is to becalled, this is why it isconsidered as an example ofpolymorphism.Because in differentconditions the output isdifferent. Since, the call isdetermined duringcompile time thats why itis called compile timepolymorphism.

109

Function overriding is an example of Runtimepolymorphism.Function Overriding: When child class declaresa method, which is already present in the parentclass then this is called function overriding, herechild class overrides the parent class.

In case of function overriding we have two definitions ofthe same function, one is parent class and one in childclass. The call to the function is determined at runtimeto decide which definition of the function is to be called,thats the reason it is called runtime polymorphism

Runtime Polymorphism

110

Virtual Functions: Pointers-indirection Operators A virtual function is a member function in base class that

you expect to redefine in derived classes.

111 www.rahuldiwate.com (Prof. R.B.Diwate)

We defined three pointer objects s, c and sqof classes shape, circleand square respectively. And, we called loadFeatures() member function of each objects.

112 www.rahuldiwate.com (Prof. R.B.Diwate)

Implement Loader class

113

Memory Management, this pointer Every object in C++ has access to its own address

through an important pointer called this pointer. The thispointer is an implicit parameter to all member functions.Therefore, inside a member function, this may be used torefer to the invoking object.

Friend functions do not have a this pointer, becausefriends are not members of a class. Only memberfunctions have a this pointer.

114 www.rahuldiwate.com (Prof. R.B.Diwate)

115 www.rahuldiwate.com (Prof. R.B.Diwate)

116 www.rahuldiwate.com (Prof. R.B.Diwate)

Chain function calls on a single object.

117 www.rahuldiwate.com (Prof. R.B.Diwate)

Pointers to Objects

Output:10

118 www.rahuldiwate.com (Prof. R.B.Diwate)

119

120 www.rahuldiwate.com (Prof. R.B.Diwate)

121 www.rahuldiwate.com (Prof. R.B.Diwate)

new and delete

122 www.rahuldiwate.com (Prof. R.B.Diwate)

Pointer to derived classes,

123 www.rahuldiwate.com (Prof. R.B.Diwate)

Function pointers,

124 www.rahuldiwate.com (Prof. R.B.Diwate)

A function’s name can also be used to get functions’address. For example, in the below program, we haveremoved address operator ‘&’ in assignment. We have alsochanged function call by removing *, the program stillworks.

125 www.rahuldiwate.com (Prof. R.B.Diwate)

126 www.rahuldiwate.com (Prof. R.B.Diwate)

Pure Function A function is called pure function if it always returns the

same result for same argument values and it has no sideeffects like modifying an argument (or global variable) oroutputting something. The only result of calling a purefunction is the return value. Examples of pure functionsare strlen(), pow(), sqrt() etc. Examples of impurefunctions are printf(), rand(), time(), etc.

If a function is known as pure to compiler then Loopoptimization and subexpression elimination can beapplied to it. In GCC, we can mark functions as pure usingthe “pure” attribute.

127 www.rahuldiwate.com (Prof. R.B.Diwate)

Sometimes implementation of all function cannot be provided ina base class because we don’t know the implementation. Such aclass is called abstract class. For example, let Shape be a baseclass. We cannot provide implementation of function draw() inShape, but we know every derived class must haveimplementation of draw().

A pure virtual function (or abstract function) in C++ is a virtualfunction for which we don’t have implementation, we onlydeclare it. A pure virtual function is declared by assigning 0 indeclaration.

128 www.rahuldiwate.com (Prof. R.B.Diwate)

129 www.rahuldiwate.com (Prof. R.B.Diwate)

Pure virtual

130 www.rahuldiwate.com (Prof. R.B.Diwate)

131 www.rahuldiwate.com (Prof. R.B.Diwate)

Reference Text Books: 1. E. Balagurusamy; “Object oriented programming with C++”; 4th Edition,Tata

McGraw-Hill. 2. Herbert Schildt; “Java: The Complete Reference”; 7th Edition, Tata McGraw

Publication. Reference Books: 1. R. Lafore; “The Waite Group's Object oriented Programming in C++”; 3rd

Edition, Galgotia Publications. 2. E. Balagurusamy; “Programmmng with Java”;5thEdition,Tata McGraw-Hill. 3. Cay S Horstmann, Gary Cornell; “Core Java 2 Volume –I ”, 8th Edition, Pearson

Education. 4. BjarneStroustrup;“ Object-Oriented Programming in C++ ” ;4th Edition, Sams

Publishing. Web Resource: Google

132 www.rahuldiwate.com (Prof. R.B.Diwate)