SlideShare a Scribd company logo
1 of 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.
Static class members
In 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
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
}
#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();->0
y.getcount();->0
z.getcount();->0
x.getdata(100);
y.getdata(200);
z.getdata(300);
x.getcount();->3
y.getcount();->3
z.getcount();->3
getch();
return 0;}
Ommit this
statement would
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.
Object1
number
Object2
number
Object3
number
100
3
300200
count
Common to all three objects
#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 30
300 300 300
30
S3
i
20
S2
i
10
S1
i
300
count
(Common to all three objects)
Static member function
How 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;
#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();1
t2.showdata();2
t3.showdata();3
return 0;
}
“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
this pointer
Example 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.
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);
};
Characteristics of friend function
1. 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 program
10. Function definition need not required any scope resolution operator.
Example on friend function
Class 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;
}
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 data type
- new operator allocates sufficient memory to hold an object of type
data type and return the address of the object.
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;
-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];
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;
}
Create objects using new
class 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
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.
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.
• 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
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 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.?
Operator overloading
a1 = 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.
• 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
datatype
Operator is a keyword
Operator 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- :?
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.
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
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.
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.
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
#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.5
c2 = 1.6 + j2.7
c3 = 4.1 + j6.2
//Example program for binary operator overloading
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 farhenheitn";
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 Celsius
class 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.
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.
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
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.
#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.
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(); }
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();
}
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;
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.
Inheritance supports the reusability mechanism.
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 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
};
Syntax of derived class declaration
class 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.
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
};
 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 class
2. Private members cannot be inherithed.
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
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
6. 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()
{
cout<<“enter a and bn”;
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;// wrong
d.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 student1;
student1.
get_no(001);
student1.
get_marks(65,90);
student1.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 execute
- 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
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.
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()
{
};
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.

More Related Content

What's hot

Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3Atif Khan
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Sakthi Durai
 
object oriented programming using c++
 object oriented programming using c++ object oriented programming using c++
object oriented programming using c++fasalsial1fasalsial1
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and objectFajar Baskoro
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan collegeahmed hmed
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingSyed Faizan Hassan
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsMarlom46
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++M Hussnain Ali
 

What's hot (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C++ classes
C++ classesC++ classes
C++ classes
 
C++ classes
C++ classesC++ classes
C++ classes
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
Java Notes
Java NotesJava Notes
Java Notes
 
object oriented programming using c++
 object oriented programming using c++ object oriented programming using c++
object oriented programming using c++
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 

Similar to Unit vi(dsc++)

Object oriented design
Object oriented designObject oriented design
Object oriented designlykado0dles
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptxsyedabbas594247
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptmanomkpsg
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Abu Saleh
 
Lecture-11 Friend Functions and inline functions.pptx
Lecture-11 Friend Functions and inline functions.pptxLecture-11 Friend Functions and inline functions.pptx
Lecture-11 Friend Functions and inline functions.pptxrayanbabur
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfismartshanker1
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Abu Saleh
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptxMrMudassir
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdfKUNALHARCHANDANI1
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objectskhaliledapal
 

Similar to Unit vi(dsc++) (20)

Object oriented design
Object oriented designObject oriented design
Object oriented design
 
DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
object oriented programming language.pptx
object oriented programming language.pptxobject oriented programming language.pptx
object oriented programming language.pptx
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
Class and object
Class and objectClass and object
Class and object
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
Lecture-11 Friend Functions and inline functions.pptx
Lecture-11 Friend Functions and inline functions.pptxLecture-11 Friend Functions and inline functions.pptx
Lecture-11 Friend Functions and inline functions.pptx
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Lecture 2 (1)
Lecture 2 (1)Lecture 2 (1)
Lecture 2 (1)
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objects
 

Recently uploaded

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

Recently uploaded (20)

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

Unit vi(dsc++)

  • 1. 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.
  • 2. Static class members In 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
  • 3. 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 }
  • 4. #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();->0 y.getcount();->0 z.getcount();->0 x.getdata(100); y.getdata(200); z.getdata(300); x.getcount();->3 y.getcount();->3 z.getcount();->3 getch(); return 0;} Ommit this statement would get linker error
  • 5. • 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 count Common to all three objects
  • 6. #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 30 300 300 300 30 S3 i 20 S2 i 10 S1 i 300 count (Common to all three objects)
  • 7. Static member function How 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;
  • 8. #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();1 t2.showdata();2 t3.showdata();3 return 0; }
  • 9. “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
  • 10. this pointer Example 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.
  • 11. 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); };
  • 12. Characteristics of friend function 1. 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 program 10. Function definition need not required any scope resolution operator.
  • 13. Example on friend function Class 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; }
  • 14. 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 { ……… ………. }
  • 15. 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
  • 16. 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 data type - new operator allocates sufficient memory to hold an object of type data type and return the address of the object.
  • 17. 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;
  • 18. -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];
  • 19. 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; }
  • 20. Create objects using new class 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
  • 21. 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.
  • 22. 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.
  • 23. • 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
  • 24. 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; }
  • 25. • 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; }
  • 26. • 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.?
  • 27. Operator overloading a1 = 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.
  • 28. • 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 datatype Operator is a keyword Operator 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- :?
  • 29. 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.
  • 30. 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
  • 31. 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.
  • 32. 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.
  • 33. 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
  • 34. #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.5 c2 = 1.6 + j2.7 c3 = 4.1 + j6.2 //Example program for binary operator overloading
  • 35.
  • 36. 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.
  • 37. 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 }
  • 38. 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 farhenheitn"; 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
  • 39. • 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.
  • 40. • 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
  • 41. Convert Fahrenheit to Celsius class 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
  • 42. Conversion function in destination class: constructor function • Class ABC// destination class { public: ABC(XYZ xy) { …….. ……… } }; Class XYZ// source class ( ……… ………. }; Object of the source class.
  • 43. 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.
  • 44. 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
  • 45. 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.
  • 46. #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.
  • 47. 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(); }
  • 48. 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(); }
  • 49. 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;
  • 50. 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. Inheritance supports the reusability mechanism. A B C D Base class A B C D E Derived class
  • 51.  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 };
  • 52. Syntax of derived class declaration class 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.
  • 53. 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 };
  • 54.  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 class 2. Private members cannot be inherithed.
  • 55. 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
  • 56. Types of Inheritance 1. Single Inheritance 2. Multilevel Inheritance 3. Multiple Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance 6. Multipath Inheritance
  • 57. 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
  • 58. 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
  • 59. 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 bn”; 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;// wrong d.mul(); d.display(); Return 0; }//main
  • 60. 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
  • 61. 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 };
  • 62. 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; }
  • 63. Multiple Inheritance - A class is derived from more than one base class is called multiple inheritance. A B C Example child motherfather
  • 64. class A { //members of A }; class B { //members of B }; Derived class syntax: class c: public A, public B { //members of c ---- };
  • 65. 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 execute - Use scope resolution operator.
  • 66. Hierarchical Inheritance -two or more classes are derived from a single base class is called hierarchical inheritance. A B C SNIST IT CSE ECM
  • 67. 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 };
  • 68. 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.
  • 69. 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; } };
  • 70. 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
  • 71. 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.
  • 72. 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
  • 73. 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() { };
  • 74. 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.