What is OOPs Oop is a programming paradigm

  • Slides: 169
Download presentation
What is OOPs • Oop is a programming paradigm that represents the concept of

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.

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

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

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

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.

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

• Classes are generally declared using the keyword class, with the following format: • class_name { access_specifier_1: member 1; access_specifier_2: member 2; . . . } 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:

 • private members of a class are accessible only from within other members

• 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 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:

 • Class Crectangle • { int x, y; Public: void set_values (int, int);

• 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.

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

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)

What are variables • A variable provides us with named storage that our programs

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:

Type Description bool Stores either value true or false. char Typically a single octet(one

Type Description bool 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.

Variable Definition in C++: • A variable definition means to tell the compiler where

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.

 • Variables can be initialized (assigned an initial value) in their declaration. The

• 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.

 • Try the following example where a variable has been declared at the

• 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

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

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

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

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.

 • Abstraction refers to providing only essential information to the outside world and

• 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

Inheritance • Inheritance is the process by which objects of one class acquire the

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 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.

Polymorphism • Polymorphism is another important OOP concept. • A greek term means the

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.

Applications Of OOPs • Main application areas of OOP are • Ø User interface

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.

Benefits Of Oops. • The main advantages are • Ø It is easy to

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.

Specifying a class • A class is a way to bind the data and

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 declaration 2. 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_name { private: variable declaration; function declaration; public: variable declaration; function declaration; };

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

• #include <iostream> • #include<conio. h> • using namespace std; • • // Class Declaration class person { //Access - Specifier public: • • • //Varibale Declaration string name; int number; };

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

• • //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; }

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

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.

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

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 }

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

• The membership label class-name: : tells the compiler that the function-name belongs to 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”; • }

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

• 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 call another member function directly

 • • • • • #include <iostream> class Rectangle { int width, height;

• • • • • #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; }

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

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;

 • • • • • #include<iostream. h> #include<conio. h> class account { long

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

 • • • • • void main() { clrscr(); account a[10]; long int

• • • • • 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 tt Balance"; { for(i=0; i<10; i++) { if(a[i]. getbalance()>5000) a[i]. showdata(); } } getch(); }

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

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.

Accessing Public Member • The public members of a class can be accessed outside

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.

 • • • #include<iostream. h> #include<conio. h> class abc { int a; public:

• • • #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;

 • void main() • { • clrscr(); • abc a 1; • a

• void main() • { • clrscr(); • abc a 1; • a 1. b=20; //public member can be accessed • a 1. get(10); • cout<<"n B="<<a 1. b; • a 1. show(); • getch(); • }

Accessing private Data Member • The private data member of class are not accessible

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.

 • • • • • #include<iostream. h> #include<conio. h> class student { int

• • • • • #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; }

 • void main() • { • clrscr(); • student s 1; • s

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

Constructors • A class constructor is a special member function of a class that

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.

 • • • • #include <iostream> using namespace std; class Line { public:

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

 • • • • • void Line: : set. Length( double len )

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

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

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.

Types of Constructors • Constructors are classified into three types, namely • Default constructor

Types of Constructors • Constructors are classified into three types, namely • Default constructor • Parameterized • Copy Constructor

Default Constructor • A default constructor is a constructor that has an empty parameter

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

 • • • • • #include<iostream. h> #include<conio. h> class`constructor { int a,

• • • • • #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<<"t. B: "<<b; }; void main() { clrscr(); constructor c; //Implicit calling constructor cc=constructor(); getch(); }

Parameterized Constructor • When different objects need to be initialized with different values, a

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.

 • • • • #include<iostream. h> #include<conio. h> class constructor { int a,

• • • • #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<<"n. B: "<<b; } };

 • void main() • { • clrscr(); • constructor c(10, 15); • constructor

• 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(); • }

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

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.

 • • • • • • #include<iostrem. h> #include<conio. h> class constructor {

• • • • • • #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<<"n. A: "<<a<<"n. B: "<<b; }

 • void main() • { • clrscr(); • constructor c(10, 15); • constructor

• 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(); • }

Constructor With Default Argument • The parameterized constructor that has all default arguments can

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.

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

• class constructor • { • int a, b; • public: • • constructor(int n, int m=11) • { • a=n; • b=m; • } • void show() • { • cout<<"n. A: "<<a<<"n. B: "<<b; • };

 • void main() • { • clrscr(); • constructor c(10); • constructor cc=constructor(20,

• 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(); • }

Dynamic Initialization of Objects • Parameterized constructors can also be used to dynamically initialize

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.

 • • • • #include<iostream. h> #include<conio. h> class constructor { int a,

• • • • #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<<"t. B: "<<b; } };

 • void main() • { • clrscr(); • int x, y; • cout<<"n.

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

Access Functions • An access function is a short public function whose job is

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

 • • • • • • • #include<iostream. h> #include<conio. h> #include<string. h>

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

 • • • • • void setid(int i) { id =i; } void

• • • • • void setid(int i) { id =i; } void setbasic(int bsal) { basic_sal=bsal; } }; void main() { clrscr(); employee emp; emp. set. Name("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();

Copy Constructor • A copy constructor is a constructor that initializes a new object

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

 • • • • • • • #include<iostream. h> #include<conio. h> class constructor

• • • • • • • #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<<"n. A: "<<a<<"t. B: "<<b; }

 • void show() • { • clrscr(); • constructor c(10, 15); • constructor

• 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(); • }

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

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

 • • • • • #include<iostream. h> #include<conio. h> class destruct { int

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

 • void main() • { • clrscr(); • destruct d; • d. get();

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

Structures • Structure is a collection of variables under a single name. • Variables

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

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

• • • • #include<iostream. h> #include<conio. h> struct customer { int custnum; int salary; foat commission; }; void main() { clrscr(); customer cust 1={100, 2000, 35. 5}; customer cust 2; cout<<"n Customer Number: "<<cust 1. custnum<<": "<<"salary Rs: "<<cust 1. salary<<": "<<"Commission rs"<<cust 1. commisiion; cust 2=cust 1; cout<<"n Customer Number: "<<cust 1. custnum<<": "<<"salary Rs: "<<cust 1. salary<<": "<<"Commission rs"<<cust 1. commisiion; }

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

Pointer to Objects • When accessing members of a class given a pointers to object, use the arrow(->) operator instead of the dot operator

 • • • • • • • • #include<iostream. h> #include<conio. h> class

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

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

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.

 • • • • • • • #include<iostream. h> #include<conio. h> class student

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

 • • • • int student: : c; void main() { clrscr(); student

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

Static Function Member • The member functions declared as static can access only other

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.

 • • • • • • • • #include<conio. h> #include<stdio. h> class

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

 • • • • void main() { clrscr(); student s 1, s 2,

• • • • void main() { clrscr(); student s 1, s 2, s 3; s 1. get(); s 2. get(); s 3. get(); cout<<"n Object 1 data"; s 1. show(); cout<<"nn. Object 2 data"; s 2. show(); cout<<"nn. Object 3 data: "; s 3. show(); student: : show_count(); getch(); }

UNIT III

UNIT III

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

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.

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

• 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+object 2;

 • All operators except the following are overloaded. 1) member access operator(. ,

• 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.

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

• 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).

 • Rules to be kept in mind while overloading operators are: – The

• 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.

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

- 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.

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

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 function Operator: is c++ keyword Op : operator being overloaded. Parameter_list: list of arguments

Overloading assignment operator • Like other member operator functions, the assignment operator is also

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; • }

Overloading Arithmetic operators(binary) • (+, -, *, /, %) These operators are all binary

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.

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

• • • #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<<"nn. ANSWER IS : "<<no; }

 • • • • • FLOAT operator+(FLOAT); FLOAT operator*(FLOAT); FLOAT operator-(FLOAT); FLOAT operator/(FLOAT);

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

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

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

 • • • • • void main() { clrscr(); FLOAT a, b, c;

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

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

#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 s 3; strcpy(s 3. str, str); strcat(s 3. str, ""); strcat(s 3. str, s. str); return s 3; } };

 • • • • void main() { clrscr(); add a 1, a 2,

• • • • void main() { clrscr(); add a 1, a 2, a 3; a 1. getdata(); a 2. getdata(); a 3=a 1+a 2; cout<<"string 1: "; a 1. showdata(); cout<<"string s 2: "; a 2. showdata(); cout<<"after concatenation: "; a 3. showdata(); getch(); }

Overloading relational operator • There are various relational operators supported by C++ language like

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.

 • As an example, the C++ string class (in header <string>) overloads these

• 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 str 1 == str 2 to compare the contents of two string objects. • Stream insertion and extraction (<<, >>): For example, you can use cout << str 1 and cin >> str 2 to output/input string objects. • Strings concatenation (+, +=): For example, str 1 + str 2 concatenates two string objects to produce a new string object; str 1 += str 2 appends str 2 into str 1. • 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, str 1 = str 2 assigns str 2 into str 1.

 • #include <iostream> • class Distance • { • private: int feet; Int

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

Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); }

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; } };

 • • • • int main() { Distance D 1(11, 10), D 2(5,

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

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

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.

 • Features • Friendships are not corresponded – If class A is a

• 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.

Friend Function • One of the important concept of OOP is data hiding, i.

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 nonmember 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.

 • If a function is defined as a friend function then, the private

• 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.

 • Friend functions have the following properties: • 1) Friend of the class

• 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.

 • • • • • #include<iostream. h> #include<conio. h> class egfriend { friend

• • • • • #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; } };

 • • • • void main() { clrscr(); egfriend ef; ef. getdata(); cout<<"n

• • • • 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; }

 • • • • class A { private: int data; public: A(): data(12){

• • • • 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 d 1, B d 2) • { • return (d 1. data+d 2. data); • }

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

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

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

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, do. Task() and do. Task(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.

 • When you call an overloaded function or operator, the compiler determines the

• 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.

 • • • • • #include <iostream> class print. Data { public: void

• • • • • #include <iostream> class print. Data { 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; } };

 • • • int main() { print. Data pd; pd. print(5); pd. print(500.

• • • int main() { print. Data pd; pd. print(5); pd. print(500. 263); pd. print("Hello C++"); return 0; }

Overloading unary operator using friend function • All unary operator that can be overloaded

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.

 • • • class point { private: int x, y; public: point(int i,

• • • 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 &p 1); • }; • • • void operator++(point &p 1) { p 1. x++; p 1. y++; }

 • • • void main() { clrscr(); point p 1(2, 2); p 1.

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

Overloading binary operator using friend function • All binary operators that can be overloaded

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.

 • • • • • #include<iostream. h> #include<conio. h> class abc { int

• • • • • #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); };

 • • • • • • abc operator +(abc &bc, abc &ac) {

• • • • • • 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 a 1, a 2, a 3; a 1. get(); a 2. get(); cout<<"object 1 Data"; a 1. show(); cout<<"n Object 2 data"; a 2. show(); cout<<"n Addition"; a 3=a 1+a 2; a 3. show(); getch(); }

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

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)

#include<iostream. h> #include<conio. h> #include<process. h> Class abc { int a[5]; Public: void get()

#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]

UNIT IV Inheritance

UNIT IV Inheritance

Inheritance • In object-oriented programing (OOP) inheritance is a feature that represents the "is

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.

 • Each subclass inherits state (in the form of variable declarations) from the

• 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.

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

• 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.

Base class and derived class • A class can be derived from more than

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:

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

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

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

• 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.

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

• • • Class Base { public: int a; protected: int b; private: int c; }; • • • class Derived: public Base { void do. Something() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error } };

 • • • int main() { Derived obj; obj. a = 10; //Allowed

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

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

• 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.

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

• • • 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 do. Something() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error } }; • •

 • • • class Derived 2: public Derived { void do. Something. More()

• • • class Derived 2: public Derived { void do. Something. More() { 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 • }

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

• 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.

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

• • • Class Base { public: int a; protected: int b; private: int c; }; • • • class Derived: protected Base { void do. Something() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error } };

 • • • class Derived 2: public Derived { void do. Something. More()

• • • class Derived 2: public Derived { void do. Something. More() { a = 10; //Allowed, a is protected member inside Derived & Derived 2 is public derivation from Derived, a is now protected member of Derived 2 b = 20; //Allowed, b is protected member inside Derived & Derived 2 is public derivation from Derived, b is now protected member of Derived 2 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 } • • •

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

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.

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

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

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

• 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.

#include<iostream. h> #include<conio. h> class person { char name[30]; int age; public: void getdata()

#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; } };

class employee { int salary; public: void getsal() { cout<<"Enter salary: "; cin>>salary; }

class employee { int salary; public: void getsal() { cout<<"Enter salary: "; cin>>salary; } void showsal() { cout<<"nsalary: "<<salary; } }; class fulltime: public person, public employee { };

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. getdata(); f. getsal();

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. getdata(); f. getsal(); cout<<"nn. Employees Info: "; f. showdata(); f. showsal(); getch(); }

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

• Hierarchical inheritance • In this inheritance, more than one derived classes are created from a single base.

 • Hybrid inheritance • This is combination of more than one inheritance. Hence,

• 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.

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

Member Access Specifier How Members of the Base Class Appear in the Derived Class 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.

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

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.

 • Following example further explains concept of inheritance : class Shape • {

• 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; • };

 • • class Rectangle: public Shape { public: float area () { return

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

 • int main () • { • Rectangle rect; • Triangle tri; •

• 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 Rectangle area 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 Triangle area 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()

Single level inheritance • • • • • //inheritance single level #include<iostream. h> #include<conio.

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; } };

 • • • • • • class deepak : public abc { private:

• • • • • • class deepak : public abc { private: int m 1; int m 2; int t; public: void read 1() { cout<<"enter m 1 , m 2"<<endl; cin>>m 1>>m 2; t= m 1+m 2; } void display 1() { cout<<"m 1 "<<m 1<<endl; cout<<"m 2 "<<m 2 <<endl; cout<<"total "<<t<<endl; } };

 • • • void main() { deepak ob; clrscr(); ob. read 1(); ob.

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

 • • • • • • • //Example for Single inheritance #include<iostream. h>

• • • • • • • //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; }

 • • • • • • • void sample: : getinfo() { cout<<"Enter

• • • • • • • 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(); }

Multiple Inheritance #include<iostream. h> #include<conio. h> class person { char name[30]; int age; public:

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; } };

class employee { int salary; public: void getsal() { cout<<"Enter salary: "; cin>>salary; }

class employee { int salary; public: void getsal() { cout<<"Enter salary: "; cin>>salary; } void showsal() { cout<<"nsalary: "<<salary; } }; class fulltime: public person, public employee { };

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. getdata(); f. getsal();

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. getdata(); f. getsal(); cout<<"nn. Employees Info: "; f. showdata(); f. showsal(); getch(); }

Ambiguity Resolution in Multiple Inheritance • In multiple inheritance an ambiguity may arise when

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.

#include<iostream. h> #include<conio. h> class person { char name[30]; int age; public: void getdata()

#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; } };

class employee { int salary; public: void getdata() { cout<<"Enter salary: "; cin>>salary; }

class employee { int salary; public: void getdata() { cout<<"Enter salary: "; cin>>salary; } void showsal() { cout<<"nsalary: "<<salary; } }; class fulltime: public person, public employee { };

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. getdata(); //Ambiguity cout<<"nn.

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. getdata(); //Ambiguity cout<<"nn. Employees Info: "; f. showdata(); f. showsal(); getch(); }

Resolving Ambiguity #include<iostream. h> #include<conio. h> class person { char name[30]; int age; public:

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; } };

class employee { int salary; public: void getdata() { cout<<"Enter salary: "; cin>>salary; }

class employee { int salary; public: void getdata() { cout<<"Enter salary: "; cin>>salary; } void showsal() { cout<<"nsalary: "<<salary; } }; class fulltime: public person, public employee { };

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. person: : getdata();

void main() { clrscr(); fulltime f; cout<<"Enter employees data: "; f. person: : getdata(); f. employee: : getdata(); cout<<"nn. Employees Info: "; f. showdata(); f. showsal(); getch(); }

Hierarchical Inheritance • Hierarchical Inheritance is a type of inheritance in which more than

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.

#include<iostream. h> #include<conio. h> class employee { char name[30]; int age; public: void getdata()

#include<iostream. h> #include<conio. h> class employee { char name[30]; int age; public: void getdata() { cout<<"n. Enter name and age: "; cin>>name>>age; } void showdata() { cout<<"Name: t"<<name<<"t. Age: t"<<age; } };

class fulltime: public employee { int salary; public: void getsal() { cout<<"n. ENter salary";

class fulltime: public employee { int salary; public: void getsal() { cout<<"n. ENter salary"; cin>>salary; } void showsal() { cout<<"nsalary"<<salary; } };

class contract: public employee { int hrs_worked; int wages_perhr; public: void calsal() { cout<<"n.

class contract: public employee { int hrs_worked; int wages_perhr; public: void calsal() { cout<<"n. ENter number of hours worked: "; cin>>hrs_worked; cout<<"n. ENter wages per hour"; cin>>wages_perhr; } void showcalsal() { }; cout<<"n. Totalsalary: "<<hrs_worked*wages_perhr; }

void main() { clrscr(); fulltime f; cout<<"Enter fulltime employee data: "; f. getdata(); f.

void main() { clrscr(); fulltime f; cout<<"Enter fulltime employee data: "; f. getdata(); f. getsal(); cout<<"n. Enter contract employee data: "; contract c; c. getdata(); c. calsal(); cout<<"n. Fulltime employee info: "; f. showdata(); f. showsal(); cout<<"ncontract employees detail: "; c. showdata(); c. showcalsal(); getch(); }