Unit-VI

Post on 13-Jan-2016

36 views 0 download

Tags:

description

Unit-VI. Constructors-default constructor parameterized constructor constructor initialization list copy constructor Destructors Static class members this pointer friend functions and classes Dynamic memory management with operators new and delete. Overloading-functions. - PowerPoint PPT Presentation

Transcript of Unit-VI

Unit-VI Constructors-default constructor parameterized constructor constructor initialization list copy constructor Destructors 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.

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

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

When object t created, it is not initializing the data members of class. It is performed by a call to the function display

Display function cannot initialize its members when the object created.

constructors

• A constructor is a special member function whose task is to initialize the objects of its class when they are created. This is also known as automatic initialization of objects.

• It is special because its name is the same as the class name• The constructor is executed automatically whenever an

object of its associated class is created• It is called constructor because it constructs the values of

data members of the class.• The constructor is executed every time an object of that

class is created.

Syntax for class with a constructor:

class classname{

//private memberspublic:

classname(); //constructor declaration--------------------

};classname :: classname (void) //constructor definition {

} The constructor is invoked automatically when

the objects of that class are created . No need to write the special statement.

Example of constructor

• Class test { int a,b; test(int x,int y); }; test::test(int x,int y){ a=x; b=y; cout<<“a=“<<a’; cout<<“b=“<<b; }

void main(){ test t(10,20); test s(40,50); }

output a=10 b=20 a=40 b=50

Characteristics of constructors • Constructor name is same as class name.• They should be declared in the public section• They are invoked automatically when the objects are

created• They do not have return types, not even void and

therefore, they cannot return values.• Constructor can access any data members but cannot

be invoked explicitly.• They cannot be inherited, through a derived class can

call the base class constructor• Like other , they can have default arguments• They make ‘implicit calls’ to the operators new and

delete when memory allocation is required• Note: when a constructor is declared for a class,

initialization of the class objects become mandatory

Types of constructors

-There are three types of constructors

1) Default constructor2) Parameterized constructor3) Copy constructor

Default constructor

-constructor without arguments\ parameters is called default constructor.

- default constructor name is same as class name.- default constructor does not include return-type,

not even void.- default constructor does not return any value.- default constructor is invoked implicitly after

creation of the objects (no need to invoke explicitly).

example• Class test

{

public:

test();

};

test :: test()

{

cout<<“constructor called”;

}

void func()

{

test t2;

cout<<“func()”;

}

Void main() { test t1; cout<<“\n main”; func(); }//main

Output

constructor called. main constructor called. func()

2.Parameterized constructor

• constructor which takes parameters is called Parameterized constructor.

-Parameterized Constructor name is same as class name.-Parameterized Constructor does not include return-type, not even void.-Parameterized Constructor does not return any value.-Parameterized Constructor is invoked implicitly with parameters after

creation of the object (no need to invoke explicitly).ex: class test {

int m, n;public: test (int x, int y); // parameterized constructor ---------- ----------

}; test :: test (int x, int y)

{ m=x; n=y;

} test t1;// it wont work.

When the constructor is parametirized, we must provide appropriate arguments for the constructor.

• We must pass some initial values as arguments to the constructor when an object is created.

• This can be done in two ways.

1. explicitly.

2. implicitly.

1. test t1= test(10,20);// explicitly

2. test t1(20,30);// implicit call.

#include<iostream.h>Class integer{ int m,n; public: integer(int,int); void display( ) { cout<<“m=“<<m<<“\n”; cout<<“n=“<<n<<“\n”;}//display()};//class

Integer:: integer(int x,int y){ m=x; n=y;} main(){ integer I1(0,100); // constructor called implicitly integer I2= integer(10,20);// constructor called explicitly cout<<“\n object1”<<“\n”;I1.display();Cout<<“\nobject2”<<“\n”;I2.display(); return 0;}//main

Copy constructor- Constructor can also accepts the address of its own class

as an argument. In such case the constructor is called copy constructor.

-Copy constructor is a member function which is used to initialize an object from another object.

-Copy Constructor name is same as class name.-Copy Constructor takes one parameter that is object. -Copy Constructor does not include return-type, not even

void.-Copy Constructor does not return any value.-Copy Constructor is invoked implicitly with object as

parameter after creation of the object (no need to invoke explicitly).

• Ex-

class A

{

public:

A(&A);

};

#include<iostream.h>class point{ int a; public: point( ) //Default constructor { a=1000; } point(int x) //Parameterized constructor { a = x; } point(point &p) //Copy constructor { //p is an alternative name (alias) of object

p1 a = p.a; }void display( ) {

cout<<endl<<”a value is “<<a; } };void main( ){point p1; point p2(500); point p3(p1); p1.display();p2.display();p3.display();}

Destructor-Destructor is a member function which is used to destroy an object when an object is no longer needed.-Destructor name is same as class name preceded by tilde mark (~).-Destructor does not include return-type, not even void.-Destructor does not return any value.- Destructor cannot be overloaded.

- Single destructor is used in a class without arguments.-Destructor is invoked when the object goes out of the scope.• If no user-defined destructor exists for a class, the compiler

implicitly declares a destructor.• Ex: class X

{ public:

X(); // Constructor for class X

~~X(); // Destructor for class X };

include<iostream.h>class test{ public: test( ); //Default constructor ~ test();}; test:: test() { cout<<“\n constructor of a class”;} test :: ~test() { cout<<“\n destructor of a class”;}void main( ){ test T; //constructor is invoked after creation of object p cout<<“\n main(); }// object T goes out of the scope, destructor is called.

Example for no of objects created and alive.

int count=0;

class test

{

public:n

test()

{ count++;

cout<<“no of objects created\n”<<count;

}

~test()

{

cout<<“\n no of objects destroyed”<<count;

count--;

}

Void main()

{ cout<<“\n main”;

test t1,t2,t3,t4;

{ cout <<“\n block1”; test t5; }//out of scope { cout<<“\n block2”; test t6;}// out of scope cout<<“\n re – enter main”; }//main

Over loaded constructors

• over loading means same thing is used for different purposes.

• ex- computer.• When more than one constructor function is defined

in a class, we can say that constructor is overloaded.• all the constructors have the same name as its

corresponding class. However, they differ in their signature ( No. of arguments, data types of their arguments or both)

Class test

{

private:

int a,b,c;

public:

test()// constructor1

{

cout<<“\n enter a ,b,c “;

cin >>a>>b>>c;

}

// constructor 2

test(int x,int y,int z)

{

a=x;

b=y;

c=z

}

test ( int x, int y)// constructor 3 { a=x; b=y; c=60;} void display() { cout<<ä=“<<a<<“\n”; cout<< “b=“<<b<<“\n”; cout<< “c=“<<c<<“\n “; }};Int main() { test t1;//constructor1 test t2(10,20,30);// constructor 2 test t3(40,50);// constructor 3 t1. display(); t2.display(); t3.display();Return 0;}

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

accessible to all objects of the class.

Syntax

class class name

{

static data type data member;

………

};

data type class name:: data member=initial values;

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

Initialization is optional

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.

• The static data members should 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.

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

#include<iostream.h>#include<conio.h>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;clrscr();x.getcount();->0//y.getcount();->0//z.getcount();->0

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

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

Omit this statement out get linker error

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

Static member function

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.

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

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

};

#include<iostream.h>#include<conio.h>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;}

this pointer-this pointer is a pointer which points to the currently invoked object.

-this pointer can be used inside the member functions only.Example program#include<iostream.h>class test{ private:

int a; public: void setdata(int x) { a=x;// normal way to set data cout<<“address of my object”<<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.

#include<iostream.h>#include<conio.h>class test{ int x,y,z; public: test(int x ,int y) { this->x=x; this->y=y; }void display() { cout<<“X:"<<x<<“Y:”<<y; }};

int main(){ clrscr(); test t(10,20); t.display(); return 0;}

Output: X:10 y:20

#include<iostream.h>#include<string.h>class person{ int age; char * name; public: person(){}; person(char* p, int i ) { strcpy(name ,p) ; age = i;} person greater(person x) { if (x.age>=age) return x; else return *this; } void display() { cout<<endl<<"Age is "<<age; cout<<endl<<"Name is "<<name; }};

void main(){ clrscr(); person a ("ram" ,30), b("sam" , 35); person p; p=a.greater(b); //currently invoking object is a

p.display(); a.display();

}

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

};

1. Function should preceded by keyword friend2. The function is defined any where in the program3. Function definition need not required any scope resolution operator.4. Its not a member function of the class.however, access to private members of a class.

Characteristics of friend function

1. Function name is preceded by the keyword friend.2. The scope of the friend is not limited to the class in

which it has been declared.3. Since it is not in the scope of the class, It cannot be

invoked using the object of that class.4. Invoked like a normal function.5. It can be declared either in the public or the private

part of a class.6. It takes object as an argument.7. 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.

Example on ffClass 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 void main(){ abc ab; xyz xy; ab.setdata(10); xy.setdata(20); cout<<“sum of the two no=“ <<add(ab,xy);}

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{……………….}

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

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 operator.• New 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 datatype - new operator allocates sufficient memory to hold an object of type data type and return the address of the object.-Example int *p; p=new int; 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

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

Pointer- variable= new datatype[size];

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.

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;

Example on new and delete

• #include<iostream.h> int main() { char *name; name=new char[]; cout<<“enter the name”; cin>>name; cout<<name; delete [ ] name; return 0;}

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

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 come

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.

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

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

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

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

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.

• Operator overloading is one of the method of achieving polymorphism in c++.

• We can perform more actions with the single operator.

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

• 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#(arg-list);

Here, the Return_type is commonly name of the class itself#- can be replaced by the any valid operator such as +, -, *, <, etc.

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.

• The following operators cannot be overloaded.

1. class member access operators(.,.*)

2. scope resolution operator.

3. sizeof() operator.

4. conditional operator- :?

Overloading unary operator(++,--) class ABC { private: int index; public: ABC( ) { index=0; } int getindex() { return index; } 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.

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); t1=t1+t2;// t1=t1.operator+(t2); t1.show();}//main

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 types

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

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 }

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

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

• 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

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

Conversion function in destination class: constructor function

• Class ABC// destination class { public:

ABC(XYZ xy) { ……..

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

Object of the source class.

Inheritance

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

B

C

D

Base class

A

B

C D

E

Derived class

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

Syntax of derived class declaration

class derivedclassname:[visibility mode] baseclassname{ //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.

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

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

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

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.

protected mode.

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

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

Public inheritance:

Private inheritance

Protected variables:

When a derived class is used as a base class for another derived class, any protected member of the initial base class that is inherited(as public) by the first derived class may also be inherited as protedted again by a second derived class as shown below:

Protected Inheritance:

Types of Inheritance

1. Single Inheritance2. Multilevel Inheritance3. Multiple Inheritance4. Hierarchical

Inheritance5. Hybrid Inheritance6. Multipath Inheritance

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

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

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() { 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() { 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

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

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

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 r1; r1.get_no(001); r1.get_marks(65,90); r1.display(); return 0;}

Multiple Inheritance- A class is derived from more than one base class is called multiple inheritance.

A B

C

Example

child

motherfather

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

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

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.

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

A

B C

SNIST

IT CSE ECM

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

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.

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

};

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

Multipath Inheritance or Virtual base classes-Derivation of a class from other derived classes, which

are derived from the same base class is called multipath inheritance.

-Multipath inheritance involves more than one form of inheritance namely multilevel, multiple, and hierarchical.

Grand parent

Parent1

Parent2

Child

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

};

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

Function Template:

#include<iostream.h>template <class T>T add(T a,T b){ return (a+b);}

int main(){ int i=10,j=20; cout<<add(i,j)<<endl; cout<<add(2.5f,3.5f); //cout<<add(2,'a'); return 0;

}

Template:

#include<iostream.h>template <class T>class Test{ T a,b; public: Test(T i,T j) { a=i;b=j; } void show() { cout<<"a:"<<a<<" b: "<<b; }};

int main(){ Test<int> t1(2,4); Test<float> t2(2.5f,3.5f); t1.show(); t2.show(); return 0;}

Class Template:

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.

• General form

derived constructor(arl1,ar2,…arlN):

base1(arl1),base2(arl2)…. baseN(arlN)

{

// body of derived constructor.

}

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

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