C Dydydydy634664
C Dydydydy634664
C++
UNIT-IV
C++ : Introduction, simple program, standard library, header files, inline functions, references and
reference parameters, default arguments, empty parameter lists, unary, scope resolution operator,
function overloading, function templates.
Classes and data abstraction : Class scope, accessing class members, interfere, constructions, destructions, const objects
and member functions, this pointer, new and delete operators, static class members.
UNIT-V
C++ Inheritance : Base and derived classes, casting base class, pointers to derived class pointers,
using member functions overriding, public, protected and private inheritance, constructors and
destructors in derived classes.
C++ Virtual Functions : Abstract base class, polymorphism, dynamic binding, virtual destructors.
C++ Templates : Introduction, class templates, templates and inheritance, templates and static
members.
1
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
2
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
HISTORY OF C++:
C++ was written by Bjarne Stroustrup at Bell Labs during 1983-1985.
He had combined the Simula 's use of classes and object-oriented features with the
power and efficiency of C.
3
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
PROPERTIES OF OOPS
1) OBJECT
2) CLASS
3) INHERITANCE
4) POLYMORPHISM
5) ABSTRACTION
6) ENCAPSULATION
7) DYNAMIC BINDING
8) MESSAGE PASSING
Object
Class
Class is a collection of objects
Class is a common name given to a group of objects
4
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
For example: IT-1 is name of class. Each and every student present in IT-1 class is
said to be a object.
In computer terminology class is called as collection of data and functions.
Properties of object are represented by data (variables)
Behaviour of object is represented by functions of the class.
Example:
2.
Objects Class
Apple, mango,grapes,orange etc.,, Fruit
Pink,blue,black,yellow etc.,, Color
5
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Inheritance
One class using the properties of another class is said to be inheritance. Ex:
parents - children
Code reusability is achieved through inheritance
Class whose properties are used by other class is called as BASE CLASS.
Class which uses the properties of other class is said to be DERIVED CLASS.
6
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Polymorphism
Ability to exist in different forms is said to be polymorphism.
POLY means MANY
MORPHISM means FORMS
Example:
I. * is used for multiplication and also for declaring a pointer variable
II. >> and << are used for right and left shift of bit operations and also along with
cin and cout in CPP.
Example of polymorphism
Abstraction
7
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
hiding the actual content and showing only the required content is said to be
abstraction.
Example: index of text book, google search engine etc.,,
Advantage of abstraction is every user will get his/her own view of the data.
Example
ENCAPSULATION:
DYNAMIC BINDING
Link between function call and function procedure is made at run- time.
Dynamic binding is also called as late binding or run-time binding.
MESSAGE PASSING:
#include<iostream>
using namespace std;
main()
{
int a,b,c;
cout<<"enter 2 integers";
cin>>a>>b;
cout<<(a+b);
}
Using >> or << more than one time in a statement is known as CASCADING.
Example: cout<<a<<b; or cin>>a>>b;
>> is called as extraction operator, which is used to extract values from key board
9
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
If the name of local and global variables is same then to differentiate both of them
we use unary scope resolution operator.
Scope resolution operator is denoted by ::
#include<iostream>
using namespace std;
int k=20;
//global variable
main()
{
int k=40;
cout<<k; //40
cout<< ::k; //20
}
INLINE FUNCTION
#include<iostream>
using namespace std;
inline square(int h)
{
return h*h;
}
main()
{
cout<< square(5);
}
output: 25
10
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
In the above code when function call is made that is when square(5) is executed by
compiler the function definition will be replaces the function call.
This happens when a function is preceded by the keyword “inline”
Advantage of inline function is that control of the program will be with main() only.
Disadvantage is for each function call a separate copy of function definition is created
in memory.
Note:
Inline function may not work if it contains any loop (s),switch,goto,static varibles.
Inline function cant be recurive.
member function defined inside the class are inline
REFERENCE VARIABLE
reference is a substitute for an object.
A variable which is used to provide an alternative name for a previously defined
variable is called as REFERENCE VARIABLE.
(ampersand) & operator is used before the name of the variable.
Syntax is:
datatype &var_name=var_name;
Example:
int x=10;
int &y=x;
cout<<x; //10
cout<<y; //10
REFERENCE TO A REFERNCE:
int x=10;
int &y=x;
int &m=y;
int &k=m;
cout<<x; //10
cout<<y; //10
cout<<m; //10
cout<<k //10
11
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
FUNCTION OVERLOADING
Functions having same name differ by number and type of arguments is called
function overloading.
#include<iostream>
using namespace std;
void show()
{
cout<<"no arguments";
}
int show(int x)
{
return x * x;
}
float show(float m)
{
return m;
}
main()
12
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
{
show();
show(4.3f,2.6f);
cout<<show(25);
cout<<show(6.7f);
}
NOTE:
Function overloading should be done with caution. That is we should not overload
function that are not related to each other.
Also if we are using classes and objects in function overloading then all the functions
should be present in the same class.
Functions of different classes cannot be overloaded.
class class_name
{
private: var_declaration;
function declaration;
public: var_declaration;
function declaration;
protected: var_declaration;
function declaration;
};
13
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Protected members can be accessed by a class and its derived class, and also by the
derived class of the derived class.
Program to find average of 3 numbers using the concept of class, object and
member function
#include<iostream>
using namespace std;
class demo
{
private:
int x,y,z;
float k;
public:
void input(int,int,int);
void output();
void average();
};
void demo::output()
{
cout<<k;
14
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
void demo::average()
{
k=(x+y+z)/3;
}
main()
{
demo d;
d.input(10,20,30);
d.average();
d.output();
}
15
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
FRIEND FUNCTION
“friend” is a keyword.
Friend function is used to access the private data of the class.
Friend function takes object of a class as an argument
Friend function cannot refer members of class directly. It uses the object to refer them
Friend function cannot be called using object of class, it should be called directly.
Normal values cannot be passed as arguments in friend function.
#include<iostream>
using namespace std;
class demo
{
private: int x,y,z;
public:
void input(int,int,int);
};
main()
{
demo d;
d.input(10,20,30);
cout<< average(d);
}
CONSTRUCTOR
17
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
1. Default constructor
When a class is created then compiler automatically allocates a constructor
called as default constructor.
2. Non-parameterized constructor
Constructor with no parameters
3. Parameterized constructor
Constructor with parameters
4. Copy constructor
Passing object as an argument.
That is initializing object of one class with other object of same class is
called copy initialization.
Such a constructor is called as copy constructor
“ OVERLOADING OF CONSTRUCTOR MEANS GIVING A
DIFFERENT MEANING TO THE CONSTRUCTOR.”
demo(int a,int b)
{
x=a; y=b;
cout<<(x+y);
}
demo(demo m)
{
x = m.x;
cout<<x;
}
};
demo :: demo(float k)
{
f=k;
cout<<f;
}
main()
{
demo d1;
demo d2(10);
demo d3(20,30);
demo d4(5.4f);
demo d5(d2);
demo d6;
d6=d2;
demo d7=d2;
}
19
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
DESTRUCTOR
demo()
{
c++;
cout<<"created object"<<c;
}
~demo()
{
cout<<"destroyed object"<<c;
c--;
}
};
main()
{
cout<<"enter main";
demo d1,d2,d3;
{
20
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
cout<<"block-1";
demo d4;
}
{
cout<<"block-2";
demo d5;
}
cout<<"re-enter main";
}
OPERATOR OVERLOADING
1. Unary operators
2. Binary operators
3. Special operators
4. Insertion and extraction operators
21
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Unary operators are operators that act upon only single operand.
Example: ++, - -, -
Binary operators are operators acting upon two operands
Example: +, /.%,<,> etc.,
Operators like new,delete,(,),[,] etc., are special operators.
>> and << are extraction and insertion operators.
#include<iostream>
using namespace std;
class unary
{
int a,b;
public:
void get();
void display();
void operator -();
};
void unary::get()
{
cout<<"enter the values of a and b"<<"\n";
cin>>a>>b;
}
void unary:: display()
{
cout<<"a= "<<a<<" ,b= "<<b<<endl;
}
void unary::operator -()
{
22
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
a=-a;
b=-b;
}
main()
{
unary u1;
u1.get();
u1.display();
-u1;
u1.display();
}
PROGRAM FOR CREATION OF COMPLEX CLASS WITH OPERATOR
OVERLOADING (binary operator overloading)
#include<iostream>
using namespace std;
class complex
{
float x,y;
public:
complex()
{
x=0;
y=0;
}
void display()
23
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
{
cout<<x<<" "<<y<<endl;
}
};
the overload opearator must have at least on operand tha is of user defined type
we can not change the basic meaning of an operator i.e we can not use + for subtraction
overload operators follow the syntax rules of the orginal opearators.they cannot be
overriden.
24
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Binary operators overloaded through a member function function take one explicit
argument and those which are overloaded through a friend function take 2 explicit
arguments.
When using binary operators overloaded through a member function, the left hand
operand must be an object of the relvant class.
Binary arithmetic operator such as +,-,*,and / must explicitly return a value.They must
not attempt to change their own arguments.
TEMPLATES
Template is a mechanism that makes one function or class to handle many kinds of
data types.
When templates are used with functions they are function templates
When templates are used with classes they are class templates or generic classes.
#include <iostream.h>
template <class T>
T max(T &a, T &b)
{
if(a>b)
return a;
else
return b;
}
25
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
main()
{
cout << max(10, 20);
cout << max(‘v’,’m’);
cout << max(3.5f,4.5f);
}
After seeing a function template compiler remembers it for future use.
Compiler will not generate any code using function template since it don’t know that
kind of data it is going to handle.
When a function call is made depending on the type of values passed compiler
substitutes that data type in place of ‘T’ in the function template.
#include<iostream>
using namespace std;
template<class t>
class bubble
{
t a[20];
public:
void get(int);
void sort(int);
void display(int);
};
template<class t>
void bubble<t>::get(int n)
{
cout<<"enter elements";
for(int i=0;i<n;i++)
cin>>a[i];
}
26
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
template<class t>
void bubble<t>::display(int n)
{
cout<<"sorted array is";
for(iint i=0;i<n;i++)
cout<<a[i];
}
template<class t>
void bubble<t>::sort(int n)
{
t temp;
for(int i=0; i<n; i++)
for(int j=0;j<n-1;j++)
if(a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
main()
{
bubble<int> b1;
cout<<"integer sorting";
b1.get(5);
b1.sort(5);
b1.display(5);
bubble<char> b2;
cout<<"character sorting";
b2.get(5);
b2.sort(5);
b2.display(5);
}
27
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
“this” POINTER
#include<iostream>
using namespace std;
class sample
{
int x;
public:
sample()
{
x=10;
}
void f1(int x)
{
cout<< x;//20
cout<< this->x;//10
}
};
main()
{
sample s;
s.f1(20);
}
28
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
#include<iostream>
using namespace std;
class max
{
int a;
public:
void get()
{
cout<<"enter a";
cin>>a;
}
void compare(max m)
{
if(this->a > m.a)
cout<<"max no.is";
cout<<this->a;
else
cout<<"max. no is";
cout<<x.a;
}
};
main()
{
max p,q;
p.get();
q.get();
p.compare(q);
}
29
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
DEFAULT ARGUMENTS
#include<iostream>
using namespace std;
cout<< add(x,y);
cout<<add();
cout<<add(34);
}
int x[10];
#include<iostream>
using namespace std;
main()
{
int size,i;
cout<<"enter array size";
cin>>size;
cout"<<"enter elements";
for(i=0;i<size;i++)
cin>>p[i];
cout<<"elements are";
for(i=0;i<size;i++)
cout<<p[i];
delete [ ]p;
}
32
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
If we don’t want to modify value of some object then we can use the keyword
“const”.
If a member function does not modify any data member in the class then we can
declare it as “const” member function.
A “const” object can call only constant member function.
A non-const object can call both const member function and non-const member
function.
#include<iostream>
using namespace std;
main()
{
int x,y;
public:
demo()
{
x=0;
y=0;
}
demo(int p,int q)
{
x=p;
y=q;
}
cout<<y;
}
void display()
{
cout<<"hello";
}
};
main()
{
demo d1;
const demo d2(20,40);
d1.show();
d2.show();
d1.display();
d2.display();// error
}
STREAMS
34
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
The cin statement accepts input from keyboard and waits until user presses the
ENTER key on key board.
Then it begins processing and stores the result in the variable.
The input request for more variables is also allowed. It is shown below:
cin>>a>>b>>c;
Using >> in above way is known as CASCADING.
#include<iostream>
using namespace std;
main()
{
int a,b,c;
cout<<"enter 3 values";
cin>>a>>b>>c;
a=a+b;
b=a*b;
c=a+b+c;
cout<<a<<b<<c;
}
Note: to demonstrate input and output streams any program can be written which is
containing “cout” and “cin” objects.
35
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
INHERITANCE
In public inheritance all properties of base class are available to the derived class.
In private inheritance the private data of base class cannot be accessed directly by
derived class.
In protected inheritance the properties of base class are available to derived class
and their derived classes.
TYPES OF INHERITANCE
1. Single inheritance
2. Multi-level inheritance
3. Hierachial inheritance
36
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
4. Multiple inheritance
5. Hybrid inheritance
#include<iostream>
using namespace std;
class A
{
Public:
void display1()
{
cout<<”hello”<<endl;
}
};
Class B : public A
{
Public:
37
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
void display2()
{
vout<<”world”;
}
};
main()
{
B b1;
b1.diaplay1();
b1.display2();
}
#include<iostream>
using namespace std;
class A
{
public:
void display1()
{
cout<<”hello”<<endl;
}
};
Class B :public A
{
public:
Void display2()
{
cout<<”world”<<endl;
}
};
Class C: public B
{
public:
38
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Void display3()
{
cout<<”hai”;
}
};
main()
{
c c1;
c1.diaplay1();
c1.display2();
}
#include<iostream>
using namespace std;
class A
{
Public:
Void display1()
{
Cout<<”hello”<<endl;
} };
Class B :public A
{
Public:
Void display2()
{
Cout<<”world”<<endl;
} };
Class C: public A
{
39
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Public:
Void display3()
{
Cout<<”hai”;
} };
main()
{
B b1;
b1.display1();
b1.display2();
C c1;
c1.display1();
c1.display3();
}
#include<iostream>
using namespace std;
class A
{
Public:
Void display1()
{
Cout<<”hello”<<endl;
}
};
Class B
{
Public:
Void display2()
{
Cout<<”world”<<endl;
40
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
}
};
Class C: public A, public B
{
Public:
Void display3()
{
Cout<<”hai”;
}
};
main()
{
C c1;
c1.diaplay1();
c1.display2();
c1.display3();
}
#include<iostream>
using namespace std;
class A
{
Public:
Void display1()
{
Cout<<”hello”<<endl;
} };
Class B :public A
{
Public:
Void display2()
41
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
{
Cout<<”world”<<endl;
} };
Class C
{
Public:
Void display3()
{
Cout<<”hai”;
} };
main()
{
D d1;
d1.display1();
d1.display2();
d1.display3();
d1.display4();
}
#include<iostream>
using namespace std;
42
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
class A
{
int a;
Public:
void display1()
{
cout<<”hello”<<endl;
}
int get()
{
cin>>a;
return a;
}
};
Class B : private A
{
Public:
void display2()
{
int k;
cout<<"enter value";
cin>>k;
cout<<k*get();
} };
main()
{
B b1;
b1.diaplay1();
b1.display2();
}
FUNCTION OVERRIDING
43
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
When both base and derived classes contain same function prototypes, then derived
function will override base class function. This mechanism is known as FUNCTION
OVERRIDING.
2. Virtual function
CASTING THE BASE CLASS or POINTER TO DERIVED CLASS or DYNAMIC
BINDING or RUN-TIME POLYMORPHISM or DYNAMIC POLYMORPHISM
#include<iostream>
using namespace std;
Class Base
{
Public:
Void print()
{
Cout<<”base class function\n”;
}
};
Class Derived: public Base
{
Public:
Void print()
{
Cout<<”derived class function\n”;
}
};
main()
{
base *bp; // base pointer
base b1; // base object
derived d1; // derived object
bp=&b1; //base pointer points to base object
bp->print(); //base class print() is called
45
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
VIRTUAL FUNCTION
#include<iostream>
using namespace std;
Class Base
{
Public:
Virtual Void print()
{
Cout<<”base class function\n”;
}
};
Class Derived: public Base
{
Public:
Void print()
{
Cout<<”derived class function\n”;
}
};
main()
{
Base *Bp; // base pointer
Base b1; // base object
Derived d1; // derived object
Bp=&b1; //base pointer points to base object
Bp->print(); //base class print() is called
Bp=&d1; // base pointer points to derived object
Bp->print(); //derived class print() is called
}
#include<iostream>
using namespace std;
Class Base //abstract base class
{
Public:
Virtual Void print()=0; //pure virtual function
};
Class Derived: public Base
{
Public:
Void print()
{
Cout<<”derived class function\n”;
}
};
main()
{
Base *Bp; // base pointer
Base b1; // base object
Derived d1; // derived object
Bp=&b1; //base pointer points to base object
Bp->print(); //base class print() is called
Bp=&d1; // base pointer points to derived object
Bp->print(); //derived class print() is called
}
VIRTUAL DESTRUCTOR
#include<iostream>
using namespace std;
class base
{
public:
base()
{
cout<<"base class created";
}
~base()
{
cout<<"base class destroyed";
}
};
~derived()
{
cout<<"derived class destroyed";
48
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
} };
main()
{
base *bp = new derived();
delete *bp;
}
Output:
base class created
derived class created
derived class destroyed
base class destroyed
When you precede a member variable's declaration with static, you are telling the
compiler that only one copy of that variable will exist and that all objects of the class
will share that variable.
Unlike regular data members, individual copies of a static member variable are not
made for each object.
No matter how many objects of a class are created, only one copy of a static data
member exists. Thus, all objects of that class use that same variable.
49
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
All static variables are initialized to zero before the first object is created.
When you declare a static data member within a class, you are not defining it. (That
is, you are not allocating storage for it.)
Instead, you must provide a global definition for it elsewhere, outside the class. This
is done by re declaring the static variable using the scope resolution operator to
identify the class to which it belongs. This causes storage for the variable to be
allocated. (Remember, a class declaration is simply a logical construct that does not
have physical reality.)
To understand the usage and effect of a static data member, consider this program:
#include<iostream>
using namespace std;
class A
{
public:
static int count;
A()
{
count++;
}
};
int A::count;
main()
{
A a1,a2,a3;
cout<<"objects created "<<a1.count;
A a4,a5;
cout<<"objects created "<<A::count;
}
output:
objects created 3
objects created 5
50
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
#include<iostream>
using namespace std;
class A
{
public:
static int x,y;
A()
{
x++; y=5;
}
void static put();
};
void A::put()
{
cout<<x;
cout<<y;
}
int A::x;
main()
{
51
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
A p,q,r;
p.put();
A s,t;
A::put();
}
output: 3 5
Exception Handling
An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks
A program catches an exception with an exception handler at the place in a program where you
want to handle the problem. The catch keyword indicates the catching of an exception.
A program throws an exception when a problem shows up. This is done using a throw keyword.
52
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
Exception Description
An exception and parent class of all the standard C++
std::exception
exceptions.
std::bad_alloc This can be thrown by new.
std::bad_cast This can be thrown by dynamic_cast.
This is useful device to handle unexpected exceptions in a
std::bad_exception
C++ program
std::bad_typeid This can be thrown by typeid.
An exception that theoretically can be detected by reading
std::logic_error
the code.
53
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC
54