what is oops

169
What is OOPs Oop is a programming paradigm that represents the concept of objects that have data fields(attributes that describe the object)and associated procedures known as methods. Objects which are usually instance of classes are used to interact with one another to design applications and computer programs.

Upload: zlata

Post on 13-Jan-2016

23 views

Category:

Documents


1 download

DESCRIPTION

What is OOPs. Oop is a programming paradigm that represents the concept of objects that have data fields(attributes that describe the object)and associated procedures known as methods. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: What is OOPs

What is OOPs

• Oop is a programming paradigm that represents the concept of objects that have data fields(attributes that describe the object)and associated procedures known as methods.

• Objects which are usually instance of classes are used to interact with one another to design applications and computer programs.

Page 2: What is OOPs

What is a Object • Objects are basic run time entities in an object

oriented system.• They may represent a person, a place, a bank

account, or any item that the program has to handle.• When a program is executed, the objects interact by

sending messages to one another.• For example if customer and account are two

objects in a program, then the customer object may send a message to the account object requesting for bank balance.

• Each object contains data and code to manipulate data

Page 3: What is OOPs

What are Classes• A class is an expanded concept of a data

structure: instead of holding only data, it can hold both data and function

• We just mentioned that objects contain data and code to manipulate that data. The entire set of data and code can be made user-defined type with help of class.

• In fact objects are variable of type class.• Thus a class is collection of objects of similar type.• Classes are user defined data type but behave like

inbuilt data type.

Page 4: What is OOPs

• Classes are generally declared using the keyword class, with the following format:

• class class_name {access_specifier_1:member1;access_specifier_2:member2;...} object_names;

• Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.

• All is very similar to the declaration on data structures, except that we can now include also functions and members, but also this new thing called access specifier. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire:

Page 5: What is OOPs

• private members of a class are accessible only from within other members of the same class or from their friends.

• protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.

• Finally, public members are accessible from anywhere where the object is visible.

• By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access. For example:

Page 6: What is OOPs

• Class Crectangle• {

int x,y;Public:void set_values (int,int);int area (void);} rect;Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect. This class contains four members: two data members of type int (member x and member y) with private access (because private is the default access level) and two member functions with public access: set_values() and area(), of which for now we have only included their declaration, not their definition.

Page 7: What is OOPs

Why we need OOPs• The proper question should be WHEN (not WHY), or WHY and WHY

NOT.• t makes complex code easier to develop, more reliable, more

maintainable, and generally better. Because OOP insists that you think about what you expose to the outside world, it lets you change the implementation of an object without affecting any other code. (Encapsulation)Because it allows you to have many different functions, all with the same name, all doing the same job, but on different data. (Polymorphism)Because it lets you write generic code: which will work with a range of data, so you don't have to write basic stuff over, and over again. (Generics)Because it lets you write a set of functions, then expand them in different direction without changing or copying them in any way. (Inheritance)

Page 8: What is OOPs

What are variables

• A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

• The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive:

• There are following basic types of variable in C++ as explained in last chapter:

Page 9: What is OOPs

Type Descriptionbool Stores either value true or false.

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.double A double-precision floating point value.void Represents the absence of type.wchar_t A wide character type.

Page 10: What is OOPs

Variable Definition in C++:

• A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows:

• type variable_list; Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here:

• int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.

Page 11: What is OOPs

• Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:

• type variable_name = value; Some examples are:• extern int d = 3, f = 5; // declaration of d and f. int d

= 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = 'x'; // the variable x has the value 'x'. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.

Page 12: What is OOPs

• Try the following example where a variable has been declared at the top, but it has been defined inside the main function:

• #include <iostream> using namespace std; // Variable declaration: extern int a, b; extern int c; extern float f; int main () { // Variable definition: int a, b; int c; float f; // actual initialization a = 10; b = 20; c = a + b; cout << c << endl ; f = 70.0/3.0; cout << f << endl ; return 0; } When the above code is compiled and executed, it produces the following result:

• 30 23.3333

Page 13: What is OOPs

Basic concept of OOP• It is necessary to understand some of the

concepts used extensively in object oriented programming. These Include:

• Objects• Classes• Data Abstraction and Encapsulation• Inheritance• Polymorphism• Dynamic Binding• Message Passing

Page 14: What is OOPs

Data Abstraction and Encapsulation• The wrapping up of data and function into a single

unit(called class) is known as encapsulation.• Data Encapsulation is the most striking feature of a

class.• The data is not accessible to outside world and

only those function which are wrapped in the class can access it.

• These functions provide the interface between the object’s data and the program.

• This insulation of the data from direct access by program is called data hiding.

Page 15: What is OOPs

• Abstraction refers to providing only essential information to the outside world and hiding their background details.

• Data Abstraction is a programming technique that relies on the separation of interface and implementation.

• E.g. TV• Which you can turn on and off, change the channel,

adjust the volume, and add external components such as speakers, VCRs and DVD.

• But you do not know how it receives signal over the air or cables how it translates them and finally displays them on screen

Page 16: What is OOPs

Inheritance• Inheritance is the process by which objects of one

class acquire the properties of another class. It supports the concept of hierarchical classification.

• In oop the concept of inheritance provides the idea of reusability.

• This means that we can add additional features to an existing class without modifying it.

• This is possible by deriving a new class from the existing ones. The new class will have the combined features of both the classes .

• Subclass defines only those features that are unique to it.

Page 17: What is OOPs

Polymorphism• Polymorphism is another important OOP concept.• A greek term means the ability to take more than one

form.• An operation may exhibit behaviors in different instances.• The behavior depend upon the type of data used in

operation.• For example consider the operation addition if it is a

number it will generate sum but if it is two string then it will generate third string

• The process of making an operator to exhibit different behavior in different instances is known as operator overloading.

Page 18: What is OOPs

Applications Of OOPs

• Main application areas of OOP are• Ø User interface design such as windows,

menu ,…• Ø Real Time Systems• Ø Simulation and Modelling• Ø Object oriented databases• Ø AI and Expert System• Ø Neural Networks and parallel programming• Ø Decision support and office automation

system.

Page 19: What is OOPs

Benefits Of Oops.• The main advantages are• Ø It is easy to model a real system as real objects are represented by

programming objects in OOP. The objects are processed by their member data and functions. It is easy to analyze the user requirements.

• Ø With the help of inheritance, we can reuse the existing class to derive a new class such that the redundant code is eliminated and the use of existing class is extended. This saves time and cost of program.

• Ø In OOP, data can be made private to a class such that only member functions of the class can access the data. This principle of data hiding helps the programmer to build a secure program that can not be invaded by code in other part of the program.

• Ø With the help of polymorphism, the same function or same operator can be used for different purposes. This helps to manage software complexity easily.

• Ø Large problems can be reduced to smaller and more manageable problems. It is easy to partition the work in a project based on objects.

• Ø It is possible to have multiple instances of an object to co-exist without any interference i.e. each object has its own separate member data and function.

Page 20: What is OOPs

Specifying a class• A class is a way to bind the data and its associated functions together. It

allows the data (and functions) to be hidden, if necessary, from external use. When defining a class, we are creating a new abstract data type that can be treated like any other build-in data type.Generally, a class specification has two parts:1. Class declaration2. Class function definitions

• The class declaration describes the type scope of its members. The class function definitions describe how the class functions are implemented.

• The general form of a class declaration is:class class_name{private:variable declaration;function declaration;public:variable declaration;function declaration;};

Page 21: What is OOPs

• #include <iostream>• #include<conio.h>• using namespace std;

• // Class Declaration• class person• {• //Access - Specifier• public:

• //Varibale Declaration• string name;• int number;• };

Page 22: What is OOPs

• //Main Function• int main()• {• // Object Creation For Class• person obj;

• //Get Input Values For Object Varibales• cout<<"Enter the Name :";• cin>>obj.name;

• cout<<"Enter the Number :";• cin>>obj.number;

• //Show the Output• cout << obj.name << ": " << obj.number << endl;

• getch();• return 0;• }

Page 23: What is OOPs

Defining Member Function• Member functions can be defined in two places:

1. Outside the class definition.2. Inside the class definition.

It is obvious that, irrespective of the place of definition, the function should perform the same task. Therefore, the code for the function body would be identical in both the cases. However, there is a subtle difference in the way the function header is defined.

Page 24: What is OOPs

Outside the class Definition• Member functions that are declared inside a class have to

be defined separately outside the class. Their definition are very much like the normal functions. They should have a function header and a function body.

• An important difference between a member function and a normal function is that a member function incorporates a membership identity label in the header. This label tells the compiler which class the function belongs to. The general form of a member function definition is:return_type class_name :: function_name (argument declaration){function body}

Page 25: What is OOPs

• The membership label class-name:: tells the compiler that the function function-name belongs to class class-name.

• That is the scope of function is restricted to the class-name specified in the header line

• The symbol:: is called scope resolution• E.g.• Void item:: getdata (int a, float b)• {• Number=a;• Cost b;• }• Void item:: putdata(void)• {• Cout<<“Number:”<<number<<“\n”;• Cout<<“cost:”<<cost<“\n”;• }

Page 26: What is OOPs

• The member functions have some special characteristics that are often used in program development.

• Characteristics are:• Several different classes can use same

function name• Member functions can access the private data

of the class. A Non member function cannot do so

• A member function can call another member function directly

Page 27: What is OOPs

• #include <iostream>• class Rectangle• { int width, height; • public: void set_values (int,int); • int area() {return width*height;} • }; • void Rectangle::set_values (int x, int y) • { width = x; • height = y; • } • int main () • { • Rectangle rect; • rect.set_values (3,4); • cout << "area: " << rect.area(); • return 0;• }

Page 28: What is OOPs

Creating Objects• Once a class is defined it can be used to create

variables of its type known as objects.• The relation between an object and a class is

same as that of a variable and its datatype• Syntax:• Classname objectlist;

Page 29: What is OOPs

• #include<iostream.h>• #include<conio.h>• class account• {• long int acc_no, balance;• public:• void getdata()• {• cout<<"\nEnter account no and its balance:";• cin>>acc_no>>balance;• }• void showdata()• {• cout<<endl<<acc_no<<"\t"<<balance;• }• long int getbalance()• {• return balance;• }• };

Page 30: What is OOPs

• void main()• {• clrscr();• account a[10];• long int bal;• int i;• for(i=0;i<10;i++)• a[i].getdata();• cout<<endl<<"Following are the accounts having balance>5000";• cout<<endl<<"Account No \t\t Balance";• {• for(i=0;i<10;i++)• {• if(a[i].getbalance()>5000)• a[i].showdata();• }• }• getch();• }

Page 31: What is OOPs

Accessing Members of class• The members of a class can be directly

accessed inside the class using their names.• However accessing a member outside the

class depends on its access specifier.• The access specifier not only determines the

part of the program where the member is accessible, but also how it is accessible in the program.

Page 32: What is OOPs

Accessing Public Member

• The public members of a class can be accessed outside the directly using the object name and dot operator’.’.

• The dot operator associates a member with the specific object of the class.

Page 33: What is OOPs

• #include<iostream.h>• #include<conio.h>• class abc• {• int a;• public:• int b;• void getdata(int x)• {• a=x;• }

• void show()• {• cout<<"\n A="<<a;• }• };

Page 34: What is OOPs

• void main()• {• clrscr();• abc a1;• a1.b=20;//public member can be

accessed• a1.get(10);• cout<<"\n B="<<a1.b;• a1.show();• getch();• }

Page 35: What is OOPs

Accessing private Data Member

• The private data member of class are not accessible outside the class not even with the object name.

• However they can be accessed indirectly through the public member functions of that class.

Page 36: What is OOPs

• #include<iostream.h>• #include<conio.h>• class student• {• int rollno;• char name[10];• float percentage;• public:• void getdata(int r, char *s, float p)• {• rollno =r;• strcpy(name,s);• percentage p;• }• void show()• {• cout<<"\n Rollno:"<<rollno;• cout<<"\n Name""<<name;• cout<<"\n Percentage:"<<percentage;

• }

Page 37: What is OOPs

• void main()• {• clrscr();• student s1;• s1.rollno=10;//invalid• s1.name="sanjeela"//inavalid• s1.getdata(10, "sanjeela", 89.5);• s1.show();• getch();• }

Page 38: What is OOPs

Constructors

• A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

• A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables.

Page 39: What is OOPs

• #include <iostream> • using namespace std; • class Line • { • public: void setLength( double len ); • double getLength( void ); • Line(); // This is the constructor • private: double length; • }; • // Member functions definitions including constructor• Line::Line(void) • { • cout << "Object is being created" << endl; • }

Page 40: What is OOPs

• void Line::setLength( double len ) • {• length = len; • } • double Line::getLength( void )• {• return length; • }• // Main function for the program• int main( ) • { • Line line; • // set line length • line.setLength(6.0); • cout << "Length of line : " << line.getLength() <<endl; • return 0;• }

Page 41: What is OOPs

Characteristics of constructors• 1) Constructor has the same name as that of the class it

belongs.• (2) Constructor is executed when an object is declared.• (3) Constructors have neither return value nor void.• (4) The main function of constructor is to initialize

objects and allocate appropriate memory to objects.• (5) Though constructors are executed implicitly, they

can be invoked explicitly.• (6) Constructor can have default and can be overloaded.• (7) The constructor without arguments is called as

default constructor.

Page 42: What is OOPs

Types of Constructors• Constructors are classified into three types,

namely • Default constructor• Parameterized• Copy Constructor

Page 43: What is OOPs

Default Constructor• A default constructor is a constructor that has

an empty parameter list.• There can only be one default constructor in a

class. • If not defined explicitly, the complier

automatically provides a default constructor to construct the objects of a class.

• However the default constructor provided by complier initializes all the members with garbage value

Page 44: What is OOPs

• #include<iostream.h>• #include<conio.h>• class`constructor• {• int a,b;• public:• constructor()• {• cout<<"\n Enter two Numbers:";• cin>>a>>b;• cout<<"\n A:"<<a<<"\tB:"<<b;• }• };• void main()• {• clrscr();• constructor c;//Implicit calling• constructor cc=constructor();• getch();• }

Page 45: What is OOPs

Parameterized Constructor• When different objects need to be initialized

with different values, a parameterized constructor can be defined.

• A parameterized constructor is a constructor that accepts one or more parameters or arguments at the time of declaration of objects and initializes the data members of the objects with these parameters.

Page 46: What is OOPs

• #include<iostream.h>• #include<conio.h>• class constructor• {• int a,b;• public:• constructor(int n, int m)• {• a=n;• b=m;• }• void show()• {• cout<<"\n A:"<<a<<"\nB:"<<b;• }• };

Page 47: What is OOPs

• void main()• {• clrscr();• constructor c(10,15);• constructor cc=constructor c(20,30);• cout<<"Object 1 Data";• c.show();• cout<<"\n Object 2 Data";• cc.show();• getch();• }

Page 48: What is OOPs

Multiple Constructor In a Class• C++ allows defining multiple constructors with

different numbers, data types or order of parameters in a single class and it is known as constructor overloading.

• Constructor Overloading enables multiple constructors to initialize different objects of a class differently.

• These objects can be initialized with the same values or different values or with existing objects of the same class.

• In C++ a class can simultaneously have a default constructor, a parameterized constructor and a copy constructor.

Page 49: What is OOPs

• #include<iostrem.h>• #include<conio.h>• class constructor• {• int a,b;• public:• constructor()• {• a=5;• b=10;• }• constructor(int n,int m)• {• a=n;• b=m;• }• void show()• {• cout<<"\nA:"<<a<<"\nB:"<<b;• }• };

Page 50: What is OOPs

• void main()• {• clrscr();• constructor c(10, 15);• constructor cc=constructor(20,30);• constructor ccc;• cout<<"\n Object 1 Data";• c.show();• cout<<"\n Object 2 data";• cc.show();• cout<<"\n Object 3 data";• ccc.show();• getch();• }

Page 51: What is OOPs

Constructor With Default Argument

• The parameterized constructor that has all default arguments can be considered as a default constructor since it can be invoked without arguments.

• This implies that if an object is declared without parentheses, all the data members are initialized with default values.

• For eg a default constructor of form abc(int n=10) can be called either one or no argument.

• If no argument is specified it can be considered as a default constructor.

Page 52: What is OOPs

• class constructor• {• int a,b;• public:•

• constructor(int n,int m=11)• {• a=n;• b=m;• }• void show()• {• cout<<"\nA:"<<a<<"\nB:"<<b;• }• };

Page 53: What is OOPs

• void main()• {• clrscr();• constructor c(10);• constructor cc=constructor(20,30);• cout<<"\n Object 1 Data";• c.show();• cout<<"\n Object 2 data";• cc.show();• getch();• }

Page 54: What is OOPs

Dynamic Initialization of Objects• Parameterized constructors can also be used

to dynamically initialize the objects of a class.• That is the parameterized constructor can

initialize the object with the values provided by the user at run time.

• Moreover, by using multiple constructors in a class, different formats of initialization can be provided.

Page 55: What is OOPs

• #include<iostream.h>• #include<conio.h>• class constructor• {• int a,b;• public:• constructor(int n, int m)• {• a=n;• b=m;• }• void show()• {• cout<<"\nA:"<<a<<"\tB:"<<b;• }• };

Page 56: What is OOPs

• void main()• {• clrscr();• int x,y;• cout<<"\nEnter two nubers";• cin>>x>>y;• constructor c(x,y);• cout<<"\n objects Data";• c.show();• getch();• }

Page 57: What is OOPs

Access Functions

• An access function is a short public function whose job is to return the value of a private member variable.

• Access function typically come in two flavors• 1) Getters and• 2) Setters• Getters are functions that simply return the

value of a private member variable.• Setters are functions that simply set the value

of a private member variable

Page 58: What is OOPs

• #include<iostream.h>• #include<conio.h>• #include<string.h>• class employee• {• char *name;• int id;• int basic_sal;• public:• char* get_name()• {• return name;• }• int get_id()• {• return id;• }• int get_basicsal()• {• return basic_sal;• }• void setName(char *nm)• {• strcpy(name, nm);• }•

Page 59: What is OOPs

• void setid(int i)• {• id =i;• }• void setbasic(int bsal)• {• basic_sal=bsal;• }• };• void main()• {• clrscr();• employee emp;• emp.setName("Sanjeela");• emp.setid(101);• emp.setbasic(8000);• cout<<endl<<"Name:"<<emp.get_name();• cout<<endl<<"ID:"<<emp.get_id();• cout<<endl<<"Basic Salary:"<<emp.get_basicsal();

– Getch();• }

Page 60: What is OOPs

Copy Constructor• A copy constructor is a constructor that

initializes a new object of a class with the values of an existing object of the same class.

• When an object is passed as an argument to a function, a copy constructor is called instead of a normal constructor.

• This is because a copy constructor initializes the new object with the current state (value)of the existing object and not with initial stat of existing object

Page 61: What is OOPs

• #include<iostream.h>• #include<conio.h>• class constructor• {• int a,b;• public:• constructor()• {• a=5;• b=10;• }• constructor(int n, int m)• {• a=n;• b=m;• }• constructor(constructor &cp)• {• a=cp.a;• b=cp.b;• }• void show()• {• cout<<"\nA:"<<a<<"\tB:"<<b;• }• };

Page 62: What is OOPs

• void show()• {• clrscr();• constructor c(10,15);• constructor cc(c);• cout<<"\n Object 1 Data";• c.show();• cout<<"\n Object 2 data";• cc.show();• getch();• }

Page 63: What is OOPs

Class Destructor• Once an object is declared, memory space is allocated to the data

members.• The resources and memory allocated to objects must be released

when an object Is destroyed.• This is accomplished by another special member function called

destructor, which is automatically invoked to release all the resources and memory that an object acquires during its life time.

• Like a constructor destructor is also special as it has the same name as that of the class of which it is a member but with a tilde (~) prefixed to its name

• It is a complement operator, which reminds complier that destructor is a compliment of constructor.

• A destructor neither accepts parameter nor has a return value not even void, It cannot be overloaded

Page 64: What is OOPs

• #include<iostream.h>• #include<conio.h>• class destruct• {• int a;• public:• void get()• {• cout<<"\nEnter a Number:";• cin>>a;• }• void show()• {• cout<<"\nA:"<<a;• }• ~destruct()• {• cout<<"\n objects destroyed";

• }• };

Page 65: What is OOPs

• void main()• {• clrscr();• destruct d;• d.get();• cout<<"\n Object Data";• d.show();• getch();• }

Page 66: What is OOPs

Structures• Structure is a collection of variables under a

single name.• Variables can be of any type int, float, char

etc.• The main difference between structure and

array is that array is a collection of same datatype.

• The structure is declared is a keyword struct followed by structure name, also called as tag.

• Then members are defined with their type and variable

Page 67: What is OOPs

• #include<iostream.h>• #include<conio.h>• struct customer• {

int custnum;• int salary;• foat commission;• };• void main()• {• clrscr();• customer cust1={100,2000,35.5};• customer cust2;• cout<<"\n Customer Number:"<<cust1.custnum<<":"<<"salary

Rs:"<<cust1.salary<<":"<<"Commission rs"<<cust1.commisiion;• cust2=cust1;• cout<<"\n Customer Number:"<<cust1.custnum<<":"<<"salary

Rs:"<<cust1.salary<<":"<<"Commission rs"<<cust1.commisiion;• }

Page 68: What is OOPs

Pointer to Objects• When accessing members of a class given a

pointers to object, use the arrow(->) operator instead of the dot operator

Page 69: What is OOPs

• #include<iostream.h>• #include<conio.h>• class person• {• char name[20];• int age;• public:• void get()• {• cout<<"Enter name";• cin>>name;• cout<<"\nEnter age";• cin>>age;• }• void show()• {• cout<<"\n Name:"<<name;• cout<<"\n Age:"<<age;• }• };• void main()• {• clrscr();• person p;• person *ptr;• p.get();• ptr=&p;• ptr->show();• getch();• }

Page 70: What is OOPs

Static Data Member• Classes can contain static member data and member functions. When a

data member is declared as static, only one copy of the data is maintained for all objects of the class.

• Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope. These static members have external linkage.

• We can define class members static using static keyword.

• A static member is shared by all objects of the class. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

Page 71: What is OOPs

• #include<iostream.h>• #include<conio.h>• class student• {• int rollno;• char name[30];• float percent;• static int c;• public:• void get()• {• cout<<"\n Enter name";• cin>>name;• cout<<"Enter Percentage";• cin>>percent;• rollno=++c;• }• void show()• {• cout<<"\n RollNo:"<<rollno;• cout<<"\n Name:"<<name;• cout<<"\n Percentage"<<percent;• cout<<"\n Total number of students admitted";• }• };

Page 72: What is OOPs

• int student::c;• void main()• {• clrscr();• student s1, s2;• s1.get();• s2.get();• cout<<"\n object 1 data";• s1.show();• cout<<"\nobject 2 Data";• s2.show();• getch();• }

Page 73: What is OOPs

Static Function Member• The member functions declared as static can

access only other static data members and static member functions of the same class.

• Static member functions are defined by prefixing the keyword static to their return type in header of their definition inside the class.

• A static member function can be accessed using class name and scope resolution operator.

Page 74: What is OOPs

• #include<conio.h>• #include<stdio.h>• class student• {• int rollno;• char name[30];• float percent;• static int c;• public:• void get()• {• cout<<"\nEnter Name:";• gets(name);• cout<<"\nEnter percentage:";• cin>>percent;• rollno=++c;• }• void show() • {• cout<<"\nRoll NO:"<<rollno;• cout<<"\nName:"<<name;• cout<<"\nPercentage:"<<percent;• }• static void show_count()• {• cout<<"\n\n\tTotal number of students admitted:"<<c;• }• };• int student::c;

Page 75: What is OOPs

• void main()• {• clrscr();• student s1,s2,s3;• s1.get();• s2.get();• s3.get();• cout<<"\n Object1 data";• s1.show();• cout<<"\n\nObject 2 data";• s2.show();• cout<<"\n\nObject 3 data:";• s3.show();• student::show_count();• getch();• }

Page 76: What is OOPs

UNIT III

Page 77: What is OOPs

Operator Overloading• One of the key feature of c++ is that the objects of

a class can be treated like the variables of built in data types.

• That is c++ permits to perform all the arithmetic and logical operations on the variables.

• The way of giving additional meaning to operators(+,-,*,/,<,>,==) is known as operator overloading.

• It is the most important concepts of object oriented programming and is a way to implement compile time polymorphism.

Page 78: What is OOPs

• An important concept related to operator overloading is data type conversions.

• When an expression involves the variables of built-in data type, c++ automatically handles the implicit conversion of data types.

• For e.g. consider statement int n,m; int S=n+m;

• In these statement, two variables are added and a result is stored in third variable.

• However, the + operator cannot be directly used to add two objects of a class.

• object 3= object 1+object2;

Page 79: What is OOPs

• All operators except the following are overloaded.

1) member access operator(.,.*) 2) Scope Resolution Operator(::) 3) Conditional Operator(?:) 4) Preprocessor symbol (#) 5) Size of operator.

Page 80: What is OOPs

• An operator is overloaded with the help of special function called an operator function.

• It defines the operation that the overloaded operator will perform on the objects of the class for which it is redefined.

• An operator function can be defined either as a public member function of the class or as a friend function.

• To overload an operator following steps need to be performed.– Create the class for which an operator is to be overloaded.– Declare the operator function either as a public member function

of the class or friend function of same class.– Define the operator function either inside or outside the class

definition (it is a member function) and outside the class(it is a friend function).

Page 81: What is OOPs

• Rules to be kept in mind while overloading operators are:– The implementation of the operator can be

changed, however not the syntax for using the operator.

– The precedence and the associativity of an operator cannot be changed.

– The number of operands required(unary,binary) with the operator cannot be changed.

– New operators cannot be created.– Overloaded operators except the function call

operator () cannot have default arguments.

Page 82: What is OOPs

- All overloaded operators except assignment operator”=” can be inherited by derived class.

-The operator(), [], -> and = can be overloaded only as member functions and not as friend function.

Page 83: What is OOPs

Overloading using member function• The operator function defined as member function of the class

is known as member operator function.• Like other member functions of the class, the member

operator function can be defined outside or inside the class.• Syntax

return type operator op(parameter_list){function body;}

Where return type is datatype of value returned by the functionOperator:is c++ keywordOp : operator being overloaded.Parameter_list: list of arguments

Page 84: What is OOPs

Overloading assignment operator• Like other member operator functions, the

assignment operator is also overloaded as a non static public member function that accepts one parameter.

• Syntax:• Return type operator=(parameter)• { // function body;• }

Page 85: What is OOPs

Overloading Arithmetic operators(binary)

• (+, -, *, /, %) These operators are all binary operators (they take two operands).

• They do not change either operand – for example, the expression 5 + 2 does not change either 5 or 2. Therefore, an operand that is an object should be passed as a reference to a const object. If an operand is a simple built-in data type like int or float, it should be passed by value instead.

• Since binary operators operate on two operands, one operand that is, the object of the class invoking the function is passed implicitly to the member operator function.

• The other operand is passed as an argument , which can be passed either by value or by reference.

Page 86: What is OOPs

• #include<iostream.h> • #include<conio.h> • class FLOAT • { • float no; • public:

FLOAT(){} void getdata() {

cout<<"\n ENTER AN FLOATING NUMBER :"; cin>>no;

} void putdata() {

cout<<"\n\nANSWER IS :"<<no; }

Page 87: What is OOPs

• FLOAT operator+(FLOAT); • FLOAT operator*(FLOAT); • FLOAT operator-(FLOAT); • FLOAT operator/(FLOAT); • }; • FLOAT FLOAT::operator+(FLOAT a) • { • FLOAT temp; • temp.no=no+a.no; • return temp; • } • FLOAT FLOAT::operator*(FLOAT b) • { • FLOAT temp;• temp.no=no*b.no; • return temp; • }

Page 88: What is OOPs

• FLOAT FLOAT::operator-(FLOAT b)• { • FLOAT temp; • temp.no=no-b.no;• return temp; • }• FLOAT FLOAT::operator/(FLOAT b) • { • FLOAT temp; • temp.no=no/b.no; • return temp; • }

Page 89: What is OOPs

• void main() • { • clrscr(); • FLOAT a,b,c; • a.getdata(); • b.getdata(); • c=a+b; • cout<<"\n\nAFTER ADDITION OF TWO OBJECTS"; c.putdata(); • cout<<"\n\nAFTER MULTIPLICATION OF TWO OBJECTS"; • c=a*b; • c.putdata(); • cout<<"\n\nAFTER SUBSTRACTION OF TWO OBJECTS"; • c=a-b; • c.putdata(); • cout<<"\n\nAFTER DIVISION OF TWO OBJECTS"; • c=a/b; • c.putdata();• getch(); • }

Page 90: What is OOPs

#include<iostream.h>#include<conio.h>#include<string.h>class add{char str[80];public:

void getdata() { cout<<"n Enter string"; cin>>str; }void showdata(){cout<<str;}add operator+(add s){ add s3; strcpy(s3.str, str);

strcat(s3.str, ""); strcat(s3.str, s.str);

return s3;}

};

Page 91: What is OOPs

• void main()• {• clrscr();• add a1,a2,a3;• a1.getdata();• a2.getdata();• a3=a1+a2;• cout<<"string 1:";• a1.showdata();• cout<<"string s2:";• a2.showdata();• cout<<"after concatenation:";• a3.showdata();• getch();• }

Page 92: What is OOPs

Overloading relational operator• There are various relational operators

supported by C++ language like (<, >, <=, >=, ==, etc.) which can be used to compare C++ built-in data types.

• You can overload any of these operators, which can be used to compare the objects of a class.

• Following example explains how a < operator can be overloaded and similar way you can overload other relational operators.

Page 93: What is OOPs

• As an example, the C++ string class (in header <string>) overloads these operators to work on string objects:

• String comparison (==, !=, >, <, >=, <=): For example, you can use str1 == str2 to compare the contents of two string objects.

• Stream insertion and extraction (<<, >>): For example, you can use cout << str1 and cin >> str2 to output/input string objects.

• Strings concatenation (+, +=): For example, str1 + str2 concatenates two string objects to produce a new string object; str1 += str2 appends str2 into str1.

• Character indexing or subscripting []: For example, you can use str[n] to get the char at index n; or str[n] = c to modify the char at index n. Take note that [] operator does not perform index-bound check, i.e., you have to ensure that the index is within the bounds. To perform index-bound check, you can use string's at() member function.

• Assignment (=): For example, str1 = str2 assigns str2 into str1.

Page 94: What is OOPs

• #include <iostream> • class Distance • { • private: int feet; Int inches; Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; }

Page 95: What is OOPs

Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } bool operator <(const Distance& d) { if(feet < d.feet) { return true; } if(feet == d.feet && inches < d.inches) { return true; } return false; } };

Page 96: What is OOPs

• int main() • {• Distance D1(11, 10), D2(5, 11); • if( D1 < D2 ) • { • cout << "D1 is less than D2 " << endl; • } • else • { • cout << "D2 is less than D1 " << endl; • } • return 0; • }

Page 97: What is OOPs

Friend class

• The private members are accessible only inside the member functions of same class.

• A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration).

• A friend class in C++ can access the "private" and "protected" members of the class in which it is declared as a friend.

Page 98: What is OOPs

• Features• Friendships are not corresponded – If class A is a friend of class B, class

B is not automatically a friend of class A.• Friendships are not transitive – If class A is a friend of class B, and class

B is a friend of class C, class A is not automatically a friend of class C.• Friendships are not inherited – A friend of class Base is not

automatically a friend of class Derived and vice versa; equally if Base is a friend of another class, Derived is not automatically a friend and vice versa.

• Access due to friendship is inherited – A friend of Derived can access the restricted members of Derived that were inherited from Base. Note though that a friend of Derived only has access to members inherited from Base to which Derived has access itself, e.g. if Derived inherits publicly from Base, Derived only has access to the protected (and public) members inherited from Base, not the private members, so neither does a friend.

Page 99: What is OOPs

Friend Function• One of the important concept 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 access private or protected data from non-member function which is friend function and friend class.

• A friend function is a function that is not a member of a class but has access to the class's private and protected members.

• Friend functions are not considered class members; they are normal external functions that are given special access privileges.

• Friends are not in the class's scope, and they are not called using the member-selection operators (. and –>) unless they are members of another class.

• A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords.

Page 100: What is OOPs

• If a function is defined as a friend function then, the private and protected data of class can be accessed from that function. The complier knows a given function is a friend function by its keyword friend.

• The declaration of friend function should be made inside the body of class (can be anywhere inside class either in private or public section) starting with keyword friend.

• Friend functions are used mostly in two situations, firstly in operator overloading and secondly if a particular function requires to be shared between two or more classes.

• A function to be shared by two or more classes can be declared as a friend function in all classes.

Page 101: What is OOPs

• Friend functions have the following properties:• 1) Friend of the class can be member of some other class.• 2) Friend of one class can be friend of another class or all the

classes in one program, such a friend is known as GLOBAL FRIEND.

• 3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object.

• 4) Friends are non-members hence do not get “this” pointer.• 5) Friends, can be friend of more than one class, hence they

can be used for message passing between the classes.• 6) Friend can be declared anywhere (in public, protected or

private section) in the class.

Page 102: What is OOPs

• #include<iostream.h>• #include<conio.h>• class egfriend• {• friend void display(egfriend);• int n,m;• public:• void getdata()• {• cout<<"\n Enter two numbers:";• cin>>n>>m;• }• void show()• {• cout<<"\n N:"<<n;• cout<<"\n M:"<<m;• }• };

Page 103: What is OOPs

• void main()• {• clrscr();• egfriend ef;• ef.getdata();• cout<<"\n Object displayed through member function";• ef.show();• cout<<"\n object displayed through friend function";• display(ef);• getch();• }• void display(egfriend e)• {• cout<<"\n N:"<<e.n;• cout<<"\n m:"<<e.m;• }

Page 104: What is OOPs

• class A {• private:• int data;• public:• A(): data(12){ }• friend int func(A , B); • };• class B {• private:• int data;• public:• B(): data(1){ }• friend int func(A , B); • };• int func(A d1,B d2)

• {• return (d1.data+d2.data);• }

Page 105: What is OOPs

• int main()• {• A a;• B b;• cout<<"Data: "<<func(a,b);• return 0;• getch();• }

Page 106: What is OOPs

Function overloading• Function overloading or method overloading is a feature found in

various programming languages, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. It is simply defined as the ability of one function to perform different tasks.

• For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.

• Rules in function overloading• The overloaded function must differ either by the arity or data types.• The same function name is used for various instances of function

call.

Page 107: What is OOPs

• When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate overloaded function or operator is called overload resolution.

Page 108: What is OOPs

• #include <iostream> • class printData • { • public: • void print(int i) • { • cout << "Printing int: " << i << endl; • }• void print(double f) • { • cout << "Printing float: " << f << endl; • }• void print(char* c) • { • cout << "Printing character: " << c << endl; • }• };

Page 109: What is OOPs

• int main()• { • printData pd; • pd.print(5); • pd.print(500.263); • pd.print("Hello C++"); return 0; }

Page 110: What is OOPs

Overloading unary operator using friend function

• All unary operator that can be overloaded using the member function can also be overloaded using friend function.

• The friend function for unary operator accepts one argument as no implicit argument is passed to the function.

• Moreover argument is passed by reference.

Page 111: What is OOPs

• class point• {• private:• int x,y;• public:• point(int i,int j)• {• x=i;• y=j;• }

• void show()• {• cout<<"point="<<"("<<x<<","<<y<<")"<<endl;• }

• friend void operator++(point &p1);

• };

• void operator++(point &p1)• {• p1.x++;• p1.y++;• }

Page 112: What is OOPs

• void main()• {• clrscr();• point p1(2,2);• p1.show();• cout<<"after increment"<<endl;• ++p1;• p1.show();• getch();• }

Page 113: What is OOPs

Overloading binary operator using friend function

• All binary operators that can be overloaded using member function can also be overloaded using friend functions.

• The friend operator functions on binary operator accepts two arguments and both arguments are passed by reference.

Page 114: What is OOPs

• #include<iostream.h>• #include<conio.h>• class abc• {• int a,b;• public:• void get()• {• cout<<"Enter two number";• cin>>a>>b;• }• void show()• {• cout<<"\n A:"<<a<<"\n B:"<<b;• }• friend abc operator+(abc &bc, abc &ac);• };

Page 115: What is OOPs

• abc operator +(abc &bc, abc &ac)• {• abc c;• c.a=bc.a+ac.a;• c.b=bc.b+ac.b;• return c;• }• void main()• {• clrscr();• abc a1,a2,a3;• a1.get();• a2.get();• cout<<"object 1 Data";• a1.show();• cout<<"\n Object 2 data";• a2.show();• cout<<"\n Addition";• a3=a1+a2;• a3.show();• getch();• }

Page 116: What is OOPs

Overloading subscript operator• A [] Operator is overloaded as a non static member

function of class and it accepts one argument of type int.

• This argument specifies the array index of the element. However It is considered as a binary operator when overloaded.

• This is because the other operator that is calling objects is passed implicitly to the function.

• The main advantage of overloading [] operator is to implement safe array indexing.

• Syntax return type & classname :: operator [] (int)

Page 117: What is OOPs

#include<iostream.h>#include<conio.h>#include<process.h>Class abc{

int a[5];Public:

void get(){

cout<<“\n Enter 5 no.”;for(int i=0; i<5; i++)cin>>a[i]

}

Page 118: What is OOPs

UNIT IVInheritance

Page 119: What is OOPs

Inheritance

• In object-oriented programing (OOP) inheritance is a feature that represents the "is a" relationship between different classes. Inheritance allows a class to have the same behaviour as another class and extend or tailor that behaviour to provide special action for specific needs.

• Generally speaking, objects are defined in terms of classes. You know a lot about an object by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle, you would know that it had two wheels, handle bars, and pedals.

• Object-oriented systems take this a step further and allow classes to be defined in terms of other classes. For example, mountain bikes, racing bikes, and tandems are all different kinds of bicycles. In object-oriented terminology, mountain bikes, racing bikes, and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, racing bikes, and tandems.

Page 120: What is OOPs
Page 121: What is OOPs

• Each subclass inherits state (in the form of variable declarations) from the superclass. Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also, each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and tandems share some behaviours: braking and changing pedalling speed, for example.

• However, subclasses are not limited to the state and behaviours provided to them by their superclass. What would be the point in that? Subclasses can add variables and methods to the ones they inherit from the superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set of gears with a lower gear ratio.

• Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an extra set of gears, you would override the "change gears" method so that the rider could actually use those new gears.

• You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed. Methods and variables are inherited down through the levels. In general, the further down in the hierarchy a class appears, the more specialized its behaviour.

Page 122: What is OOPs

• The Benefits of Inheritance• Subclasses provide specialized behaviours from the

basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.

• Programmers can implement super classes called abstract classes that define "generic" behaviours. The abstract superclass defines and may partially implement the behaviour but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.

Page 123: What is OOPs

Base class and derived class• A class can be derived from more than one classes,

which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form:

• class derived-class: access-specifier base-class • Where access-specifier is one of public, protected, or

private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default.

• Consider a base class Shape and its derived class Rectangle as follows:

Page 124: What is OOPs

Access Specifier• Members of a class can be restricted or controlled on its access

within and outside that class. This is achieved by declaring members in either of the 3 access specifiers:

• Private access specifier:• All member of a class are restricted to be accessed only by

members of the same class and friend function and members of friend class.

• Public access specifier:• All member of a class are free to be accessed by anyone,

anywhere within and outside its class.• Protected access specifier:• All member of a class are restricted to be accessed only by

members of the same class and its direct or indirect derived classes and friend function and members of friend class

Page 125: What is OOPs

• Public Inheritance:• All Public members of the Base Class become

Public Members of the derived class &All Protected members of the Base Class become Protected Members of the Derived Class.

• i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Page 126: What is OOPs

• Class Base• {• public:• int a;• protected:• int b;• private:• int c;• };

• class Derived:public Base• {• void doSomething()• {• a = 10; //Allowed • b = 20; //Allowed• c = 30; //Not Allowed, Compiler Error• }• };

Page 127: What is OOPs

• int main()• {• Derived obj;• obj.a = 10; //Allowed• obj.b = 20; //Not Allowed, Compiler Error• obj.c = 30; //Not Allowed, Compiler Error

• }

Page 128: What is OOPs

• Private Inheritance:• All Public members of the Base Class become

Private Members of the Derived class &All Protected members of the Base Class become Private Members of the Derived Class.

Page 129: What is OOPs

• Class Base• {• public:• int a;• protected:• int b;• private:• int c;• };

• class Derived:private Base //Not mentioning private is OK because for classes it defaults to private

• {• void doSomething()• {• a = 10; //Allowed • b = 20; //Allowed• c = 30; //Not Allowed, Compiler Error• }• };

Page 130: What is OOPs

• class Derived2:public Derived• {• void doSomethingMore()• {• a = 10; //Not Allowed, Compiler Error, a is private member of Derived now• b = 20; //Not Allowed, Compiler Error, b is private member of Derived now• c = 30; //Not Allowed, Compiler Error• }• };

• int main()• {• Derived obj;• obj.a = 10; //Not Allowed, Compiler Error• obj.b = 20; //Not Allowed, Compiler Error• obj.c = 30; //Not Allowed, Compiler Error

• }

Page 131: What is OOPs

• Protected Inheritance:• All Public members of the Base Class become

Protected Members of the derived class &All Protected members of the Base Class become Protected Members of the Derived Class.

Page 132: What is OOPs

• Class Base• {• public:• int a;• protected:• int b;• private:• int c;• };

• class Derived:protected Base • {• void doSomething()• {• a = 10; //Allowed • b = 20; //Allowed• c = 30; //Not Allowed, Compiler Error• }• };

Page 133: What is OOPs

• class Derived2:public Derived• {• void doSomethingMore()• {• a = 10; //Allowed, a is protected member inside Derived & Derived2 is public

derivation from Derived, a is now protected member of Derived2• b = 20; //Allowed, b is protected member inside Derived & Derived2 is public

derivation from Derived, b is now protected member of Derived2• c = 30; //Not Allowed, Compiler Error• }• };

• int main()• {• Derived obj;• obj.a = 10; //Not Allowed, Compiler Error• obj.b = 20; //Not Allowed, Compiler Error• obj.c = 30; //Not Allowed, Compiler Error• }

Page 134: What is OOPs

Types of Inheritance• OOPs supports the five types of inheritance as

given below-• Single inheritance• In this inheritance, a derived class is created

from a single base class.

Page 135: What is OOPs

• Multi-level inheritance• In this inheritance, a derived class is created

from another derived class.

Page 136: What is OOPs

• Multiple inheritance• In this inheritance, a derived class is created

from more than one base class. This inheritance is not supported by .NET Languages like C#, F# etc.

Page 137: What is OOPs

#include<iostream.h>#include<conio.h>class person{

char name[30];int age;public:

void getdata() { cout<<"Enter name and age:";

cin>>name>>age; }void showdata() {

cout<<"Name:\n"<<name;cout<<"Age:\n"<<age;

}};

Page 138: What is OOPs

class employee{

int salary;public: void getsal() {cout<<"Enter salary:";cin>>salary; } void showsal() {cout<<"\nsalary:"<<salary; }

};class fulltime:public person, public employee{

};

Page 139: What is OOPs

void main(){

clrscr();fulltime f;cout<<"Enter employees data:";f.getdata();f.getsal();cout<<"\n\nEmployees Info:";f.showdata();f.showsal();getch();

}

Page 140: What is OOPs

• Hierarchical inheritance• In this inheritance, more than one derived

classes are created from a single base.

Page 141: What is OOPs

• Hybrid inheritance• This is combination of more than one

inheritance. Hence, it may be a combination of Multilevel and Multiple inheritance or Hierarchical .

• Since .NET Languages like C#, F# etc. does not support multiple and multipath inheritance. Hence hybrid inheritance with a combination of multiple or multipath inheritance is not supported by .NET Languages.

Page 142: What is OOPs
Page 143: What is OOPs

Member Access Specifier How Members of the Base Class Appear in the Derived Class

Private Private members of the base class are inaccessible to the derived class.

Protected members of the base class become private members of the derived class.

Public members of the base class become private members of the derived class.

Page 144: What is OOPs

Protected Private members of the base class are inaccessible to the derived class.

Protected members of the base class become protected members of the derived class.

Public members of the base class become protected members of the derived class.

Public Private members of the base class are inaccessible to the derived class.

Protected members of the base class become protected members of the derived class.

Public members of the base class become public members of the derived class.

Page 145: What is OOPs

• Following example further explains concept of inheritance :

class Shape • { • protected: • float width, height; • public: • void set_data (float a, float b) • { • width = a; • height = b; • } • };

Page 146: What is OOPs

• class Rectangle: public Shape• {• public:• float area ()• {• return (width * height);• }• };

• class Triangle: public Shape• {• public:• float area ()• {• return (width * height / 2);• }• };

Page 147: What is OOPs

• int main ()• {• Rectangle rect;• Triangle tri;• rect.set_data (5,3);• tri.set_data (2,5);• cout << rect.area() << endl;• cout << tri.area() << endl;• return 0;• }The object of the class Rectangle contains :width, height inherited from Shape becomes the protected member of Rectangle.set_data() inherited from Shape becomes the public member of Rectanglearea is Rectangle’s own public member The object of the class Triangle contains :width, height inherited from Shape becomes the protected member of Triangle.set_data() inherited from Shape becomes the public member of Trianglearea is Triangle’s own public member• set_data () and area() are public members of derived class and can be accessed from

outside class i.e. from main()

Page 148: What is OOPs

Single level inheritance• //inheritance single level• #include<iostream.h>• #include<conio.h>• class abc• {• private:• int rl;• char name[20];• public:• void read()• {• cout<<"Enter Roll No and name "<<endl;• cin>>rl>>name;• }• void display()• {• cout<<"roll no "<<rl<<endl;• cout<<"name : "<<name <<endl;• }• };

Page 149: What is OOPs

• class deepak :public abc• {• private:• int m1;• int m2;• int t;• public:• void read1()• {• cout<<"enter m1 , m2"<<endl;• cin>>m1>>m2;• t= m1+m2;• }• void display1()• {• cout<<"m1 "<<m1<<endl;• cout<<"m2 "<<m2 <<endl;• cout<<"total "<<t<<endl;• }• • };•

Page 150: What is OOPs

• void main()• {• • deepak ob;• clrscr();• ob.read();• ob.read1();• ob.display();• ob.display1();• getch();• }

Page 151: What is OOPs

• //Example for Single inheritance• #include<iostream.h>• class test• {• public:• int a,b;• void getdata();• void display();• };• class sample:public test• {• public:• int x,y;• void getinfo();• void dis();• void sum();• };• void test::getdata()• {• cout<<"Enter a & b:"<<endl;• cin>>a>>b;• }• void test::display()• {• cout<<"a="<<a<<endl;• cout<<"b="<<b<<endl;• }

Page 152: What is OOPs

• void sample::getinfo()• {• cout<<"Enter x & Y:";• cin>>x>>y;• }• void sample::dis()• {• cout<<"x="<<x<<endl;• cout<<"y="<<y<<endl;• }• void sample::sum()• {• int s;• s=a+b+x+y;• cout<<"Sum="<<s;• }• void main()• {• sample s;• s.getdata();• s.display();• s.getinfo();• s.dis();• s.sum();• getch();• }

Page 153: What is OOPs

Multiple Inheritance#include<iostream.h>#include<conio.h>class person{

char name[30];int age;public:void getdata() { cout<<"Enter name and age:";cin>>name>>age; }void showdata() {cout<<"Name:\n"<<name;cout<<"Age:\n"<<age; }

};

Page 154: What is OOPs

class employee{

int salary;public: void getsal() {cout<<"Enter salary:";cin>>salary; } void showsal() {cout<<"\nsalary:"<<salary; }

};class fulltime:public person, public employee{

};

Page 155: What is OOPs

void main(){

clrscr();fulltime f;cout<<"Enter employees data:";f.getdata();f.getsal();cout<<"\n\nEmployees Info:";f.showdata();f.showsal();getch();

}

Page 156: What is OOPs

Ambiguity Resolution in Multiple Inheritance

• In multiple inheritance an ambiguity may arise when two or more base classes have a member with same name.

• In order to resolve such ambiguities, the name of the member is qualified with the name of the base class by using the scope resolution operator.

Page 157: What is OOPs

#include<iostream.h>#include<conio.h>class person{

char name[30];int age;public:

void getdata() { cout<<"Enter name and age:";

cin>>name>>age; }void showdata() {

cout<<"Name:\n"<<name;cout<<"Age:\n"<<age;

}};

Page 158: What is OOPs

class employee{

int salary;public: void getdata() {cout<<"Enter salary:";cin>>salary; } void showsal() {cout<<"\nsalary:"<<salary; }

};class fulltime:public person, public employee{

};

Page 159: What is OOPs

void main(){

clrscr();fulltime f;cout<<"Enter employees data:";f.getdata(); //Ambiguitycout<<"\n\nEmployees Info:";f.showdata();f.showsal();getch();

}

Page 160: What is OOPs

Resolving Ambiguity#include<iostream.h>#include<conio.h>class person{

char name[30];int age;public:void getdata() { cout<<"Enter name and age:";cin>>name>>age; }void showdata() {cout<<"Name:\n"<<name;cout<<"Age:\n"<<age; }

};

Page 161: What is OOPs

class employee{

int salary;public: void getdata()

{cout<<"Enter salary:";cin>>salary; }

void showsal() {cout<<"\nsalary:"<<salary; }

};class fulltime:public person, public employee{

};

Page 162: What is OOPs

void main(){

clrscr();fulltime f;cout<<"Enter employees data:";f.person::getdata(); f.employee::getdata();cout<<"\n\nEmployees Info:";f.showdata();f.showsal();getch();

}

Page 163: What is OOPs

Hierarchical Inheritance• Hierarchical Inheritance is a type of inheritance in

which more than one class is derived from a single base class.

• In hierarchical inheritance a base class provides members that are common to all of its derived class.

• In hierarchical inheritance each of the derived class inherits all the member of its base class.

• In addition all derived classes can directly access the public and protected members of base class .

• However one derived class cannot access the members of another derived class.

Page 164: What is OOPs

#include<iostream.h>#include<conio.h>class employee{

char name[30];int age;public:

void getdata() {

cout<<"\nEnter name and age:";cin>>name>>age;

}void showdata() {

cout<<"Name:\t"<<name<<"\tAge:\t"<<age; }

};

Page 165: What is OOPs

class fulltime:public employee{

int salary;public:

void getsal() {

cout<<"\nENter salary";cin>>salary;

}void showsal() {

cout<<"\nsalary"<<salary; }

};

Page 166: What is OOPs

class contract:public employee{

int hrs_worked;int wages_perhr;public:

void calsal() {

cout<<"\nENter number of hours worked:";cin>>hrs_worked;cout<<"\nENter wages per hour";cin>>wages_perhr;

}void showcalsal() {

cout<<"\nTotalsalary:"<<hrs_worked*wages_perhr; }

};

Page 167: What is OOPs

void main(){

clrscr();fulltime f;cout<<"Enter fulltime employee data:";f.getdata();f.getsal();cout<<"\nEnter contract employee data:";contract c;c.getdata();c.calsal();cout<<"\nFulltime employee info:";f.showdata();f.showsal();cout<<"\ncontract employees detail:";c.showdata();c.showcalsal();getch();

}

Page 168: What is OOPs
Page 169: What is OOPs