74
Unit-VI Static class members this pointer friend functions and classes Dynamic memory management with operators new and delete. Overloading-functions. overloading -Operator overloading restrictions on operator overloading. overloading unary and binary operators. type conversion. Templates. Inheritance.

Unit vi(dsc++)

Embed Size (px)

Citation preview

Page 1: Unit vi(dsc++)

Unit-VIStatic class members this pointer friend functions and classesDynamic memory management with

operators new and delete.Overloading-functions.overloading -Operator overloading restrictions on operator overloading. overloading unary and binary operators. type conversion.Templates. Inheritance.

Page 2: Unit vi(dsc++)

Static class membersIn some situations, we need to have one or more data which are

accessible to all objects of the class.Syntax class classname { static data_type data member;………}; data_type classname:: data member=initial values;

Note:- static data members should be declared inside the class and it should defined out side the class.

Initialization is optional

Page 3: Unit vi(dsc++)

Characteristics of static data members: The variable which is declared as static is initialized to zero when the first object of its class is

created. No other initialization is possible. static data members should be declared inside the class and it should defined out side the class. The static data members could be initialized during their definition out side all the member

functions. Only one copy of that member is created for the entire class and is shared by all the objects of

that class, no matter how many objects are created It is visible only within the class, but its lifetime is the entire program. Public static data members accessed through scope resolution operator or through objects.

• Class test { public:

static int a; private: static int b;};.

Void main(){ test:: a=12; test::b=19;// wrong test t; t.a=18; t.b=90;// wrong}

Page 4: Unit vi(dsc++)

#include<iostream>class item{static int count;int number;public:

void getdata(int a){

number=a;count++;

}void getcount(void){

cout<<"count:"<<count;}

};int item :: count;

int main(){item x,y,z;x.getcount();->0y.getcount();->0z.getcount();->0

x.getdata(100);y.getdata(200);z.getdata(300);

x.getcount();->3y.getcount();->3z.getcount();->3getch();return 0;}

Ommit this statement would get linker error

Page 5: Unit vi(dsc++)

• Note:- the scope and type of the static variable is defined separately outside of the class. This is necessary because the static data members are stored separately rather than as a part of object.

Object1 number

Object2 number

Object3 number

100

3

300200

countCommon to all three objects

Page 6: Unit vi(dsc++)

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

public:int i;static int

count;};int SE::count;

void main(){SE s1,s2,s3;clrscr();

s1.i=10;s2.i=20;s3.i=30;

s1.count=100;s2.count=200;s3.count=300;

cout<<s1.i<<" "<<s2.i<<" "<<s3.i<<"\n";cout<<s1.count<<" "<<s2.count<<"

"<<s3.count;

getch();}

Example program for Static Class Variable

Output:10 20

30300 300

300

30

S3 i

20

S2 i

10

S1 i

300 count

(Common to all three objects)

Page 7: Unit vi(dsc++)

Static member functionHow to declare a static member function in a class.Syntax static return_type functionname(arglist); ex static void displaly(); Characteristics of static member function:• A static function can have access to only other static members (data or functions)

declared in the same class.• Class test { static int a; int b; public:

static void display() {

cout<<“a=“<<a;// correct cout<<“b=“<<b;// wrong- since static member function can access to static members.};• Non static data cannot be access to the static member functions.• A static member function can be called using the class name (instead of its objects) as

follows

class-name :: function-name;

Page 8: Unit vi(dsc++)

#include<iostream>class test{ int x;static int count;public:void setdata(void){x=++count;}void showdata(void){cout<<"object number:"<<x<<"\n";

}static void showcount(void){cout<<"count:"<<count<<"\n";}};int test :: count;

int main(){test t1,t2; t1. setdata();t2.setdata();

test :: showcount();test t3;t3.setdata();

test ::showcount();

t1.showdata();1t2.showdata();2t3.showdata();3return 0;}

Page 9: Unit vi(dsc++)

“this” Pointer Within a member function, the this keyword is a pointer to the current object, i.e.

the object through which the function was called.

The this pointer is a constant pointer.

Every object has access to its own address through a pointer called this.

A static member function does not have a this pointer.

this pointer can be used inside the member functions only.

Member functions use the this pointer implicitly or explicitly

Implicitly when accessing members directly

Explicitly when using keyword this

Page 10: Unit vi(dsc++)

this pointerExample program#include<iostream>class test{ private:

int a; public: void setdata(int x) { a=x;// normal way to set data cout<<“address of my bject”<<this; this->a=x;// another way to set data }

void showdata() { cout<<“\n address of object for showdata()”<<this; cout<<“a=“<<a; cout<<“ this->a”<<this->a;} void main() { test t,s; t.setdata(30); t.showdata();s.setdata(40);s.showdata();}

The member function of a class always with the pointer called this, which points to the object with which the function is invoked.

Page 11: Unit vi(dsc++)

friend functions and classes Private and protected members of a class cannot be accessible to out side

the class. The non member functions cannot have an access to these data of a class.

When two classes need to access the same function- make such function to be friend to both the classes.

Allow the function to have access to the private members of these two classes.

Such a function need not be member function of any of these classes.

Friend functions• Allow the non-member function to access even the private members of a

class using the friend function or friend classes.• Friend functions are used to access private members of a class• syntax class classname { ….. ….. public: friend returntype functionname(object arg);

};

Page 12: Unit vi(dsc++)

Characteristics of friend function1. Function declaration is preceded by the keyword friend.2. Its not a member function of the class. However, access to private

members of a class.3. The scope of the friend is not limited to the class in which it has been

declared.4. Since it is not in the scope of the class, It cannot be invoked using the

object of that class.5. Invoked like a normal function.6. It can be declared either in the public or the private part of a class.7. It takes object as an argument.8. Unlike the member functions, it cannot access the class members directly.

However, it can use the object and dot operator with each member name to access both the private and public data.

9. The function is defined any where in the program10. Function definition need not required any scope resolution operator.

Page 13: Unit vi(dsc++)

Example on friend functionClass xyz;// advanced class declaration class abc { private: int a; public:

void setdata(int x){a=x; }friend int add( abc ab,xyz xy);

};Class xyz { private:

int b; public:

void setdata(int y){b=y; }

friend int add( abc ab,xyz xy);};

int add( abc ab, xyz xy) { return ab.a+xy.b;}// a and b are private int main(){ abc ab; xyz xy; ab.setdata(10); xy.setdata(20); cout<<“sum of the two no=“ <<add(ab,xy); return 0;}

Page 14: Unit vi(dsc++)

Friend class• Whenever all the functions of one class can have access to the private

members of the another class. • It is possible to make the entire class as a friend of another class. So that all

the members of the friend class can have access to the private members of the another class.

Syntax class A { ……..……………….. friend class B;};Class B{……………….}

Page 15: Unit vi(dsc++)

Example on friend class

class ABC { private:

int a,b; public:

ABC(int x,int y) { a=x; b=y;

} // make a class XYZ as friend class to ABC friend class XYZ;}; class XYZ{ public:void display( ABC ab){ cout<<“\n a in ABC class=“<<ab.a; cout<<“\n b in ABC class=“<<ab.b;}};

void main() { ABC ab(10,20);

XYZ xy;//object of XYZ xy.display(ab); }

Display is function of friend class so that pass class object as argument

Page 16: Unit vi(dsc++)

Dynamic memory management operators new and delete

Dynamic memory allocation- the requested memory allocated during run time of the program

Dynamic memory allocation used when the amount of memory required is not known in advance.

In c, we have used malloc() and calloc() functions and free() for de allocating the memory.

In c++, we can use two unary operators like new and delete. They perform allocating and freeing the memory. They are also called free store

operators. An object can be created using the new and destroyed using the delete.

New operatorNew operator allocates the memory dynamically similar to the standard library function malloc(). general form

pointer variable=new datatype;

Pointer variable is a pointer of type data type - new operator allocates sufficient memory to hold an object of type data type and return the address of the object.

Page 17: Unit vi(dsc++)

New operator• An object is created using new, and destroyed by using delete, as and when required.• Any object created with the new within a block, will remain exist until it is destroyed

by using the delete operator. • Hence, the life time of object is under the control of programmer.- If requested memory is not available in the memory pool, new operator returns null

pointer. Example• int *p;//declaration• p=new int;// initialization

Delete operator• Object created with new is no longer needed, it must be destroyed with the

operator delete to release the memory for the reuse.• general form

delete pointer_variable; delete p; delete q;

Page 18: Unit vi(dsc++)

-Example int *p;//declaration p=new int;// initialization float *q; q=new float;

We can also combine the declaration and assignment like- int *p=new int;float *q= new float;

We can initialize the memory using new operator int *p= new int(30); float *q=new float(10.5);New can be used to create a memory dynamically for any data type like arrays, classes.General form is

Pointer- variable= new data_type[size];

Ex- int *p= new int[10];

Page 19: Unit vi(dsc++)

Example on new and delete• #include<iostream> using namespace std; int main() { char *name; name=new char[]; cout<<“enter the name”; cin>>name; cout<<name; delete [ ] name; return 0;}

Page 20: Unit vi(dsc++)

Create objects using newclass ABC{ int a,b; public:

ABC(int x,int y){

a=x;b=y;

}void display(){cout<<"\n a value is="<<a;cout<<"\n b value

is="<<b;}

};//class

int main() { ABC *ab=new ABC(10,20); ab->display(); delete ab; return 0; }//main

Page 21: Unit vi(dsc++)

Lab programs- 24/05/2014• Write a C++ program with class that prints all real solutions to the quadratic equation

ax2+bx+c=0. Read in a, b, c and use the quadratic formula. If the descremainant b2-4ac is negative, display a message stating that there are no real solutions.

2. A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and Subsequent terms are found by adding the preceding two terms in the sequence. Write a C++ program with class to generate the first n terms of the sequence.

3. Write a C++ with class program that checks whether a given string is palindrome or not.

4. Write a C++ program which implements all types of constructors.

5. Write a C++ program which implements class defined outside the class using scope resolution operator.

6. Write a C++ program which implements static class members.

7. Write a C++ program which uses this pointer

8. Write a C++ program which implements friend function.

Page 22: Unit vi(dsc++)

Compile-time polymorphism Binding of a function call to the function definition at compile time is called

compile-time polymorphism. This is also called static binding or early binding. Function overloading and operator overloading comes under compile-time

polymorphism.

Function overloading Function overloading- The process of two or more functions having same

name and different in their signature( no. of arguments, type of arguments).

However, the overloading function differ only in their return type is not allowed.Use of function overloading

Function overloading is one of the most powerful features of C++ programming language. It forms the basis of polymorphism (compile-time polymorphism).

Most of the time you’ll be overloading the constructor of a class.

Page 23: Unit vi(dsc++)

• Swapping of two numbers

void swap_float(float a, float b) { float temp; temp=a; a=b; b=temp; }

void swap_int(int a,int b) { int temp; temp=a; a=b; b=temp; }

Function overloading

Void swap(int a,int b);Void swap(float a,float b);Void swap(char a,char b);

void add(); void add(int a); void add(int a, int b); int add(int a,int b); last two functions are not overloading

Page 24: Unit vi(dsc++)

Overloading Functions that differ in terms of no of arguments

#include<iostream.h> //FUNTION PROTOTYPES int func(int i); int func(int i, int j); int main() { cout<<func(10);//func(int i)is called cout<<func(10,10);//func(int i, int j) is called return 0; } int func(int i) { return i; } int func(int i, int j) { return i+j; }

Page 25: Unit vi(dsc++)

• Overloading Functions that differ in terms of TYPE OF arguments#include<iostream.h> int func(int i); double func(double i); void main() { cout<<func(10);//func(int i)is called

cout<<func(10.201);//func(double i) is called } int func(int i) { return i; } double func(double i) { return i; }

Page 26: Unit vi(dsc++)

• include<iostream.h> int func(int i); double func(int i); int main() { cout<<func(10); cout<<func(10.201); return 0;} int func(int i) { return i; } double func(int i) { return i; }

This program wont work because you cant over load the functions if they are differ only in terms of data type they return.

Write a c++ program to calculate area of circle, rectangle, square using function overloading.?

Page 27: Unit vi(dsc++)

Operator overloadinga1 = a2 + a3;

The above operation is valid, as you know if a1, a2 and a3 are variable of in-built Data Types(int, float, double etc). But what if those are, say objects of a Class; is the operation valid?

Yes, it is, if you overload the ‘+’ Operator in the class, to which a1, a2 and a3 belong.

Operator overloading gives the special meaning to the operators such as +, -, *, /,etc. with respect to the class objects.

Using operator overloading we can extend the capability of an operator to operate on the class objects.

Page 28: Unit vi(dsc++)

• Operators are overloaded by creating operator functions either as a member or as a Friend Function of a class.

• declare using the following general form:

Return_type operator operator_symbol (arg-list);

Here, the Return_ type is commonly name of the class itself or any datatypeOperator is a keywordOperator symbol can be replaced by the any valid operator such as +, -, *, <, etc.-> it could be invoked as objectname.operator#(arg_list); or #objectname; ex- o1.operator+(a,b); or +o1;

• The following operators cannot be overloaded. 1. class member access operators(.,.*) 2. scope resolution operator.(::) 3. sizeof() operator. 4. conditional operator- :?

Page 29: Unit vi(dsc++)

Restrictions on operator overloading• The following are over loadable operators 1. arithmetic- +,-,*,/,% 2. bit- wise- &,|, ~,^ 3. logical - &&,||, ! 4. relational- >,<,==,<= 5. assignment - = 6. arithmetic assignment- +=,-=,*= 7. shift- <<, >> 8. unary- ++, -- 9. subscripting- [ ] 10. function call- () 11. dereferencing- -> 12. unary sign prefix- +, -13. Allocate and free- new, delete.

Page 30: Unit vi(dsc++)

C++ operators that can be overloaded:

C++ Operators that cannot be overloaded:

Operators that can be overloaded

+ - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[]

Operators that cannot be overloaded

. .* :: ?: sizeof

Page 31: Unit vi(dsc++)

Overloading unary operator(++,--)

class ABC { private: int index; public: ABC( ) { index=0; } int getindex() { return index; } void operator ++(){ index= index+1;}};

void main(){ ABC a1, a2; cout<<“index=“<<a1.getindex; cout<<“index=“<<a2.getindex; ++a1;// same as a1.operator++();cout<<“index=“<<a1.getindex;++a2;// same as a2.operator++();cout<<“index=“<<a1.getindex;}

Operators which are used to operate on single operand called unary operators.

Page 32: Unit vi(dsc++)

Binary Operator Overloading Binary operator takes two operands. Binary operators are + , -, *, etc., For example a plus operator takes two operands (a + b).

Syntax: return-type class-name :: operator (arglist) {

//function body}

In binary operator overloading, function takes one parameter.

The binary overloaded operator function takes the first object as an implicit operand and the second operand must be passed explicitly.

The data members of the first object are accessed without using the dot operator whereas, the second argument members can be accessed using the dot operator if the argument is an object.

Page 33: Unit vi(dsc++)

Overloading binary operator

Class test { int sub1, sub2; public: test (int x, int y){sub1=x;sub2=y;} // notice the declaration test operator +(test); void show(){cout<<sub1<<endl<<sub2;} };

test test :: operator +(test ob) { test temp; temp.sub1=sub1+ob.sub1; temp.sub2= sub2+ob.sub2; return temp;}

void main() { test t1(80,70); test t2(90,75); test t3=t1+t2;// t3=t1.operator+(t2); t3.show();}//main

Page 34: Unit vi(dsc++)

#include<iostream.h>class complex {

float x, y; public: complex(){ }

complex(float real,float imag) { x = real; y = imag;

}complex operator + (complex c);void display(void);

}; complex operator + (complex c) {

complex temp;temp.x = x + c.x;temp.y = y + c.y;return temp;

}

void complex :: display(void) {cout << x “ +j ” << y << “\n”;

} void main() {

complex c1,c2,c3;c1 = complex (2.5, 3.5);c2 = complex (1.6, 2.7);c3 = c1 + c2;cout << “c1 = ”;

c1.display();

cout << “c2 = ”;c2.display();

cout << “c3 = ”;c3.display();}

Output:c1 = 2.5 + j3.5c2 = 1.6 + j2.7c3 = 4.1 + j6.2

//Example program for binary operator overloading

Page 35: Unit vi(dsc++)
Page 36: Unit vi(dsc++)

Type conversion• Converting one data type to another data type is called type conversion.• Ex:- int a; float b=3.14; a=b; cout<<“\n a=“<<a; a= 3• What happens when they are user defined data types?• a1=a2+a3;// a1,a2,a3 are objects of the same class.

There are three un compatible types1. Conversion from basic data type to class type.2. Conversion from class type to basic data type.3. Conversion from one class type to another class type.

Page 37: Unit vi(dsc++)

1. Conversion from basic data type to class type• To convert data from a basic type to a user defined type (class type), the

conversion function should be defined in the class in the form of constructor.

• Constructor with one argument.• This constructor function takes a single argument of basic data type(int,

float,double).• In the constructor function write steps for converting basic to object type.

2. Conversion from class type to basic data type.• In this case, define a operator function in the class is called conversion

function.• Operator function is defined as an overloaded basic data- type which takes

no arguments.• It converts object to basic types and returns a basic data item.• Syntax- operator basic data type() { // steps to convert }

Page 38: Unit vi(dsc++)

class temperature{float celsius;public:temperature(){ celsius=0.0;}temperature(float fahrenheit){// fahrenheit to celsius celsius=(fahrenheit-32)*5/9; }operator float(){float f;// celsius to fahrenheit

f=((celsius*9/5)+32); return f;}

void gettemp(){ cout<<"\n enter the temparature celsius"; cin>>celsius; } void showtemp() { cout<<"\n temperature in celsius="<<celsius; }};void main(){ temperature t1,t2; float fa;cout<<"enter the temparature in farhenheit\n"; cin>>fa; t1=fa;// invokes constructor with argument t1.showtemp(); float ce; t2.gettemp(); ce=t2; // invokes the operator function cout<<"\n temparature in farhenheit"<<ce;}//main

Temparature conversion

Page 39: Unit vi(dsc++)

• Note – in previous program we called the constructor with one argument using the statement t1=fa;

• In this case the compiler first searches for the overloaded assignment operator function, if it is not found, it invokes the one- argument constructor.

• ce=t2;- same as the ce= float(t2); or ce= (float)t2;

3. Conversion from one class type to another class type.

• There is a situation where we need to convert one class type to another class type.

• Example- ab=xy; where ab is an object of class ABC and xy is an object of class XYZ.• XYZ is called source class and ABC are called destination class.

Page 40: Unit vi(dsc++)

• For this type conversion also we can use any of the conversions methods like constructor with one argument and operator conversion function.

• Choice of these two methods depends on the whether the conversion function should be used in source class or destination class.

• In source class implement the operator conversion function. • In destination class define the constructor with one argument.

Conversion function in source class: operator function • General form class ABC//destination class { ………members of class ABC ……… }; class XYZ // source class { public: operator ABC() { }};

Name of destination class.

Conversion operator function

Page 41: Unit vi(dsc++)

Convert Fahrenheit to Celsiusclass celsius{float cels;public:celsius(){cels=0.0;}celsius(float farh){ cels=farh; } void show() { cout<<"\n celsius="<<cels; }};

class farhenheit{ float f; public:farhenheit(){f=0.0;}operator celsius(){ return (celsius((f-32)*5/9)); } void gettemp() { cout<<"\n enter the temparature"; cin>>f; } };

void main() { celsius c1; farhenheit f1; clrscr(); f1.gettemp(); // uses the operator function in source class farhenheit c1=f1; c1.show(); getch(); }//main

Page 42: Unit vi(dsc++)

Conversion function in destination class: constructor function

• Class ABC// destination class { public:

ABC(XYZ xy) { ……..

……… }};Class XYZ// source class( ……………….};

Object of the source class.

Page 43: Unit vi(dsc++)

templates- whenever a function is defined it works only on particular data

type.Ex-

void swap(char a,char b) { char t; t=a; a=b; b=t;} void swap( int a, int b) {int t; t=a; a=b; b=t;}Void swap( float a,float b) {int t; t=a; a=b; b=t;}

void main() { char ch1=X,ch2=Y; swap(ch1,ch2); int x=10,y=20; swap(x,y); float p=10.5, q=20.7;Swap(p,q);}

Above program we have redefined the function for each and every data type.

Page 44: Unit vi(dsc++)

templates Templates is most recently added feature in c++. Another way of achieving reusability in oops is templates. Templates acts as a macros. It allows to develop the reusable software components like

functions and classes etc. Templates are used to support the generic programming

(works on different data types). Templates are used to create a family of classes and functions.

They works on different data types. Take add(), if u make this function as template function it

works on all data types such as adding int, float, and double. Templates are defined for both classes and functions. 1. function template 2. class template

Page 45: Unit vi(dsc++)

1.Function templates.• We need to designed a single piece of function which works on

all the data types.• Syntax template < class T,……> return type function_name ( arglist) { //body of the function } The function template is similar to normal function except variables that it uses whose data types are not known until a call to it is made.call to template is similar to the normal function and parameters can be of any type.when the compiler encounters a call to such functions, it identifies the data type of the parameters and creates a function internally and makes call to it.

Page 46: Unit vi(dsc++)

#include<iostream.h> template < class T> void swap(T a,T b) { T t; t=a; a=b; b=t; }Void main(){ char ch1,ch2; cout<<\n enter two characters” cin>>ch1>>ch2; swap(ch1,ch2);int x,y; cout<<“enter two integers”; cin>>x>>,y; swap(x,y);}//main

When compiler encounters swap(ch1,ch2); it internally creates a function of type swap(char a, char b);

Write a c++ program to implement bubble sort using the templates.

Page 47: Unit vi(dsc++)

Function with two generic type.#include<iostream.h>#include<conio.h>#include<string.h>template<class X,class Y>void display(X a,Y b){cout<<"\n a="<<a;cout<<"\n b="<<b;}void main(){ clrscr(); display(oo1,”IT”); display(89.9,”1strank”); getch(); }

Page 48: Unit vi(dsc++)

2. Class templates• Classes can also be operate on different data types.

such classes are called template classes. Class test

{ int a; int b; public: test(int x,int y) { a=x; b=y; } void display() { cout<<a<<b; }};

void main() { test t(10,20); t.display(); }

Page 49: Unit vi(dsc++)

Void main() { test<int , float>t1(10,20.5); test<char,float>t2(“hai”,23.8); t1.show(); t2.show(); }

Syntax:- template<class T1,class T2…..>

class class_name {//data members of generic types T1, T2, . . .

//functions with arguments of type T1, T2, . . . …….

};

#include<iostream.h.Template<class T1,class T2>class test { T1 a; T2 b; public: test(T1 x, T2 y) { a=x; b=y; } void show() { cout<<a<<b; }};

Once you have created a generic class, you create an object of that class using the following general form:

class-name <char, int> obj;

Page 50: Unit vi(dsc++)

InheritanceThe mechanism of deriving a new class from an existing class is known as inheritance.It is the technique of organizing the information in hierarchical form . Inheritance allows new classes to be built from older classes instead of being rewritten from scratch.Existing class is known as base class or parent class or super class and new class is known as derived class or child class or sub class.In inheritance base class members are inherited to derived class and also new members can be added to derived class.Inheritance supports the reusability mechanism.

A

B

C

D

Base class

A

B

C D

E

Derived class

Page 51: Unit vi(dsc++)

C ++, not only supports the access specifiers private and public, but also an important access specifiers protected, which is significant in class inheritance.

A class can use all the three visibility modes as illustrated below. class class_name{ private: //visible to member functions within its class . . . . //but not in derived class protected: //visible to member functions within its class . . . . //and its derived class public: //visible to member functions within its class, . . . . //derived classes and through object};

Page 52: Unit vi(dsc++)

Syntax of derived class declarationclass derived_classname:[visibility mode] base_classname{ //members of derived class //and they can access members of the base class}; The derivation of derived class from the base class is indicated by the colon

(:). The default visibility mode is private. Visibility mode specifies whether the features of the base class are privately or

protected or publicly inherited.

Page 53: Unit vi(dsc++)

The following are the four possible styles of derivation:

1. class D : private B //private derivation { //members of D }; 2. class D : protected B //protected derivation { //members of D }; 3. class D : public B //public derivation { //members of D }; 4. class D : B //private derivation by default { //members of D };

Page 54: Unit vi(dsc++)

Privately inherited 1. public members of base class become private to derived class. Therefore the

public members of the base class can only be accessed by the members of the derived class. They are inaccessible to the even objects of the derived class.

2. Private members of the base class cannot be inherited to the derived class.3. Protected members of the base class also become private to the derived class. they

can have access to the member functions of the derived class and further inheritance is possible.

Publicly inherited.1. Private members of the base class cannot be inherited.2. Public members of the base class become public to derived class.3. Protected members of the base class become protected to derived class.

Therefore they are accessible to the member functions of the derived class. And also further inheritance is possible.

protected mode.1. Public and protected members of the base class become protected to the

derived class2. Private members cannot be inherithed.

Page 55: Unit vi(dsc++)

Derived class visibilityBase class

Publicly privately protected

Private-> Not inherited Not inherited Not inherited

Protected-> protected private protected

Public->public private protected

Visibility of inherited members

Page 56: Unit vi(dsc++)

Types of Inheritance

1. Single Inheritance2. Multilevel Inheritance3. Multiple Inheritance4. Hierarchical Inheritance5. Hybrid Inheritance6. Multipath Inheritance

Page 57: Unit vi(dsc++)

Single Inheritance-A class is derived from only one base class. single inheritance.

base class:class A{//members of A}Derived class syntax:class B: public A{

//members of B};

A

B

Page 58: Unit vi(dsc++)

Single inheritance- publicly

class B { int a; public: int b; void getdata(); int get_a(); void show_a(); }; class D:public B { int c; public:

void mul();void display();

};Void B:: getdata() { a=5; b=10; }

int B:: get_a() { return a; } void B:: show_a() { cout<<“a=“<<a<<“\n”; }

void D::mul(){ c= b*get_a();} void D:: display() { cout<<“a=“<<get_a(); cout<<“b=“<<b;Cout<<“c=“<<c;}

Int main() { D d; d.getdata(); d.mul(); d.show_a(); d.display(); d.b=20;d.mul(); d.display();Return 0;}//main

Page 59: Unit vi(dsc++)

Privately inherited Single inheritance

class B { int a; public: int b; void getdata(); int get_a(); void show_a(); }; class D: B { int c; public:

void mul();void display();

};Void B:: getdata() { cout<<“enter a and b\n”; cin>>a>>b; }

int B:: get_a() { return a; } void B:: show_a() { cout<<“a=“<<a<<“\n”; }

void D::mul(){ c= b*get_a();} void D:: display() { show_a(); cout<<“b=“<<b;Cout<<“c=“<<c;}

Int main() { D d; d.getdata(); d.mul(); d.show_a();//wrong d.display(); d.b=20;// wrongd.mul(); d.display();Return 0;}//main

Page 60: Unit vi(dsc++)

Multilevel Inheritance- A class is derived from the base class, in turn derived class

become base class to other class is called multilevel inheritance.

A

B

C

father

son

Grand father

Page 61: Unit vi(dsc++)

class A{//members of A};Derived class syntax:Class B: public A{//members of B};Derived class syntax:Class C: public B{//members of C};

Page 62: Unit vi(dsc++)

class student { protected:

int roll_no; public:

void get_no(int)’ void put_no();};//student void student:: get_no(int a) { roll_no=a; } void student:; put_no() { cout<<“\n roll number=“<< roll_no<<“\n”; class test : public student { protected: float sub1; float sub2; public: void get_marks(float,float); void put_marks();};

Void test:: get_marks(float x,float y) { sub1=x; sub2=y;} void test :: put_marks() { cout<<“\n marks in sub1=:<<sub1; cout<<“\n marks in sub2=<<sub2;} class result: public test { float total; public: void display();}; void result::display(){ total= sub1+ sub2; put_no(); put_marks(); cout<<“\n total=“<<total;}

int main() { result student1; student1. get_no(001); student1. get_marks(65,90); student1.display(); return 0;}

Page 63: Unit vi(dsc++)

Multiple Inheritance- A class is derived from more than one base class is

called multiple inheritance.

A B

C

Example

child

motherfather

Page 64: Unit vi(dsc++)

class A{//members of A};class B{//members of B};

Derived class syntax:class c: public A, public B {//members of c----};

Page 65: Unit vi(dsc++)

class X { public:

void display() {

cout<<“\n class X”;}

}; class Y { public:

void display(){cout<<“\n class Y”;

}}; class Z: public X,public Y { public:

void display(){ X:: display();}

};

Int main() { Z z; z.display(); or z.X::display(); z Y:: display(); return 0;}

Note:- ambiguity resolution in multiple inheritance same function name is used in more than one base class ambiguity occurs which is to be executed- Use scope resolution operator.

Page 66: Unit vi(dsc++)

Hierarchical Inheritance-two or more classes are derived from a single base class is called hierarchical inheritance.

A

B C

SNIST

IT CSE ECM

Page 67: Unit vi(dsc++)

class A{//members of A};Derived class syntax:class B: public A{//members of B};Derived class syntax:class C: public A{//members of C};

Page 68: Unit vi(dsc++)

Hybrid Inheritance-Derivation of a class involving more than one form of

inheritance is known as hybrid inheritance.-Hybrid inheritance involves more than one form of

inheritance namely multilevel and multiple.

A

B C

D

1. Multilevel inheritance.2. Multiple inheritance.

Page 69: Unit vi(dsc++)

Class student { protected: int roll_no; public:

void get_no(int a){roll_no=a;}void put_no(){cout<<:\n rollno=“<< roll_no;}

Class test: public student { protected: float part1,part2; public:

void getmarks(float x,float y){ part1=x;

part2=y; }

void putmarks(){ cout<<“marks obtained”;

<<“part1=“<<part1; <<“part2=“<<part2;

}}; class sports { protected:

float score;Public:

void get_score(float s){

score=s;}void put_score(){cout<<sport wt”<<score;}

};

Page 70: Unit vi(dsc++)

Class result: public test,public sports{

float total; public: void display();}; void result:: display() { total= part1+part2+score; put_no(); putmarks(); put_score(); cout<< total score”<<total<<“\n”;} int main(){ result student1; student1.getno(001);Student1.getmarks(78.6,80.6); student1.getscore(6.0); student1.display(); return 0; }//main

Page 71: Unit vi(dsc++)

Order of constructor execution

- As long as no base class constructor takes any arguments, the derived class need not have any constructor function. However, if any base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass appropriate arguments to the base class constructor.

- In inheritance we create objects for the derived class. So that derived class should pass arguments to the base class constructor. When both the classes uses the constructors, the constructor in base is executed first and then the constructor in the derived class is executed later.

- In case of multiple inheritance, the base classes are constructed in the order in which they appeared in the declaration of derived class.

- similarly in multilevel inheritance they are executed in the order of inheritance.

Page 72: Unit vi(dsc++)

Class A { int x;Public:

A(int i){x=i;}void show_x(){cout<<?\n x=“<<x;}

}; class B { int y;Public:

B(int j){y=j;cout<<“\ny=“<<y;}

Void show_y(){

cout<<“y=“<<y;}};Class D:public B,public A { int m,n; public:D(int a,int b,int c,int d): B(a),A(b)

{m=c;n=d;}void show_mn(){ cout<<“m=“<<m<<“\n”;cout<<“n=“<<n<<“\n”;}

};

int main() { D d(5,6,7,8); d.show_x(); d.show_y();d. show_mn();Return 0;}//main

Page 73: Unit vi(dsc++)

Order of invocation of constructors

• Method of inheritance order of execution 1. class D:public B B() { D() }; 2. class D:public B1,public B2 B1() { B2() }; D()3. Class D: public B1,virtual B2 B2() { B1() }; D()4. Classs D1:public B B() { D1() }; class D2: public D1 D2() { };

Page 74: Unit vi(dsc++)

74

Constructors and Inheritance

C++ Construction Order:

1. Base class data members are constructed in order of

declaration.

2. Base class constructor is called.

3. Derived class data members are constructed in order.

4. Derived class constructor is executed.

Destructor order (reverse of constructor order):

1. Derived class destructor is executed.

2. Derived class data members are destroyed.

3. The base class destructor is called.

4. Base class data members are destroyed.