0% found this document useful (0 votes)
12 views54 pages

C Dydydydy634664

C++

Uploaded by

memories.prk.27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views54 pages

C Dydydydy634664

C++

Uploaded by

memories.prk.27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 54

C++ NOTES

Prepared By: P.KARTHIK


Asst.Prof. ITD, MVSREC

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.

C++ Operator overloading : Fundamentals, restrictions, overloading unary / binary operators,


overloading ++ and ---.

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++ Stream Input/Output : Streams, stream output, stream input.

C++ Templates : Introduction, class templates, templates and inheritance, templates and static
members.

C++ Exception Handling : Try, throw, catch.

1
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

DIFFERENCES BETWEEN POP AND OOP


Difference
between Procedure oriented Object oriented programming
POP & programming (POP) (OOP)
OOP
1 POP emphasis on algorithms OOP emphasis on data rather than
(procedure) procedure.
2 Large programs are divided into Programs are divided into objects.
smaller programs known as
functions.
3 They have not facility to hide They have facility to hide data from
data. outside world.
4 Function can transfer data from Objects can communication with
one function to another and one each other using functions.
form to another form.
5 It does not have powerful features It contains powerful features like
like operator overloading, operator overloading, inheritance.
inheritance etc.
6 For design program it uses top- For design program it uses bottom-
down approach. up approach.
7 Examples: C, COBOL, Examples: C++, JAVA
FORTRAN etc.

In Procedure Oriented Programming:

2
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

In Object Oriented Programming

HISTORY OF C++:
 C++ was written by Bjarne Stroustrup at Bell Labs during 1983-1985.

 C++ is an extension of C. Prior to 1983, Bjarne Stroustrup added features to C and


formed what he called "C with Classes".

 He had combined the Simula 's use of classes and object-oriented features with the
power and efficiency of C.

 The term C++ was first used in 1983 .

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

 Anything that exists in the real world is said to be object


 An object may be a name of person, place or thing etc.,,
 Every object will have some property and behavior.
 Object is a variable of type class.

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:

1. Consider “student” as object

Properties of student: name, roll no, marks, height.weight, gender,color etc.,,

Behavior of student: writing, reading, listening etc.,,

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:

 Wrapping (combining) up of data and function into a single unit is called as


encapsulation.
 Data will be not accessible to external classes. Only those functions that are present in
that class can access that data.

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:

 In OOP, set of objects communicate with each other.

COUT & CIN


8
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

 cout is used to print data on the screen.


 cin is used to accept values at run-time.

Program to add two integers

#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 insertion operator, which is used to insert values on the


console( output screen)

 >> is called as extraction operator, which is used to extract values from key board

 DATA TYPES, VARIABLES, KEYWORDS, CONTROL STRUCTURES,


OPERATORS etc.,, which are used in C are also applicable in CPP also.

 Apart from the 32 keywords in C we have some more keywords in CPP.

SCOPE RESOLUTION OPERATOR

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
}

 In the above ‘k’ is decalred as both local and global variable.


 ‘k’ refers to local value that is 40.
 ‘::k’ refers to global value that is 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

It is not possible to assign a different value for a reference variable

OVERLOADING: It refers to the use of same thing for different purposes.

FUNCTION OVERLOADING
 Functions having same name differ by number and type of arguments is called
function overloading.

 Program to demonstrate function overloading:

#include<iostream>
using namespace std;

void show()
{
cout<<"no arguments";
}

int show(int x)
{
return x * x;
}

void show(float a,float b)


{
cout<<(a+b);
}

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

ADVANTAGES OF FUNCTION OVERLOADING ARE:

 Different values can be passed to same function


 For a programmmer it will be easy to remember the same function name every time.

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.

SYNTAX TO DECLARE CLASS IS:

class class_name
{
private: var_declaration;
function declaration;
public: var_declaration;
function declaration;
protected: var_declaration;
function declaration;
};

 private, public and protected are access specifiers or visibility labels.


 Private members can be accessed only with in class and functions of that class
 Public members can be accessed anywhere in the program

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.

SYNTAX TO DECALRE OBJECT IS:


Class_name object_name;

TO ACCESS MEMBERS OF CLASS:


Object_name.function();

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::input(int p, int q, int r)


{
x=p; y=q; z=r;
}

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

 A function can be defined either inside or outside the class.


 If it is defined outside then:
It should be written along with its class name and ::
 For example,
void demo::output()
{
cout<<k;
}
( refer the adjacent program, input(int,int,int), output() and average() are member
functions)

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.

Program to demonstrate friend function

#include<iostream>
using namespace std;
class demo
{
private: int x,y,z;
public:
void input(int,int,int);

friend void average(demo );

};

void demo::input(int p,int q,int r)


{
x=p; y=q; z=r;
}
float average(demo m)
{
float k;
k=(m.x+m.y+m.z)/3.0;
}
16
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

main()
{
demo d;
d.input(10,20,30);
cout<< average(d);
}

CONSTRUCTOR

 In c-language values will be passed through function call as:


function_name(arguments);
 In cpp it is done as follows:
Values are passed by calling the function along with object name.
 In c-language variables are initialized at the time of declaration itself.
 That is, int x =10;
 In the same way, in order to enable an object to pass values at the time of its creation
only, we use a special member function called as CONSTRUCTOR.
 Constructor is a special member function that is called automatically when an
object is created to a class.
PROPERTIES OF CONSTRUCTOR:
 Constructor is a member function with same name as class.
 Constructor can take values as arguments
 Constructor will not have any return type since it can’t return values.

 Syntax of constructor is:


class_name()
{
….
….
}

17
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

 Types of constructors are:

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

Program for constructor overloading and copy constructor


#include<iostream>
using namespace std; demo d5(d2);
class demo demo d6;
{ d6=d2;
private: int x,y; demo d7=d2;
float f;
public:  The above
demo() statements calls the
{ copy constructor
cout<<"no arguments";
} demo(demo m)
{
x = m.x;
demo(int a) cout<<x;
{ }
x=a;
cout<<x;  one object of a class
can call only one
constructor 18
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

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

 constructor is called automatically when an object is created for the class


 Destructor is a member function which is automatically called when an object of
the class is destroyed or terminated.

 Syntax is: ~class_name()


{
}

Program to demonstrate destructor


#include<iostream>
using namespace std;
int c=0;
class demo
{
public:

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

 Destructor can’t take values and can’t return values also.

OPERATOR OVERLOADING

 The mechanism of giving a different meaning to an operator is known as operator


overloading.
 Operator overloading is done by using a special member function called as
“OPERATOR” function.

 Syntax of operator function is:


return_type classname:: operator op(arguments)
{
Statements;
}

 op means the operator that is to be overloaded.

 Types of operators are:

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.

Types of operator overloading is:

1. Unary operator overloading


2. Binary operator overloading

PROGRAM FOR UNARY OPERATOR OVERLOADING

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

complex( float r, float i)


{
x=r;
y=i;
}

complex operator +(complex);

void display()
23
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

{
cout<<x<<" "<<y<<endl;
}
};

complex complex:: operator +(complex C)


{
complex t;
t.x=x+C.x;
t.y=y+C.y;
return(t);
}
main()
{
complex c1(2.6,3.6),c2(4.6,5.6),c3;
c3=c1+c2;
c1. display();
c2.display();
c3.display();
}

RULES FOR OPERATOR OVERLOADING

 Only existing opearators can be overloaded.New opearators can not be created

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

 sizeof,.(membership opearator),. *(pointer to member opearator) ,:: (scope resolution


operator),?: (conditional operator) can’t be overloaded.

24
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

 =(assignment operator), ()(function call operator),[] (subscripting operator),-> (class


member access operator) can’t be overloaded using friend functions.

 Unary operators,overloaded by means of a member function take no explicit arguments


and return no explicit values,but, those overloaded by means of a friend function, take
one referenece argument(the object of the relvant class).

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

 Operator overloading can be done using friend function also

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.

Program to demonstrate function templates

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

Program to demonstrate class templates (bubble sort)

#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

 We can use multiple parameters in both class and function templates


 A specific class created from a class template is called as template class and the
process of creating a template class is known as INSTANTIATION.
 Template functions can also be overloaded.

“this” POINTER

 “this” pointer is used to represent an object that invokes a member function.

Program to demonstrate “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

Program to find maximum of 2 numbers using “this” pointer

#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

 Argument or parameter is the mechanism of passing a value from one function to


another function.
 C++ gives an option of specifying default values for the arguments while decalring a
function. These arguments having default values are known as DEFAULT
ARGUMENTS.
 Advantage of default arguments is that a function call can be made either by
passing values or without passing values.

Program to demonstrate default arguments

#include<iostream>
using namespace std;

int add(int a=20, int b=30);


main()
{
int x,y;
cout<<"enter values";
cin>> x >> y;

cout<< add(x,y);
cout<<add();
cout<<add(34);
}

int add(int a,int b)


{
return (a+b);
}

 In the above program,

 cout<< add(x,y); prints sum of x and y


30
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

 cout<<add(); takes default values 10 and 20 and prints their sum


 cout<<add(34); takes ‘a’ as 34 and ‘b’ as 20

 RULES FOR DECLARING DEFAULT ARGUMENTS ARE:-


 In function declaration values should be given starting from right side onwards.
 In function definition values should be given starting from left side onwards.

DYNAMIC MEMORY ALLOCATION

int x[10];

 For the above statement 20 bytes of memory is allocated (10*2 bytes)


 This memory is allocated when that statement is executed by compiler
 This type of allocation is known as STATIC MEMORY ALLOCATION.
 But in this kind of declaration the memory might be wasted.
 That is, in the above declaration 20 bytes of memory is allocated for 10 elements, but
if we assign only 2 elements that is only 4 bytes of memory is being used, thereby
wasting 16 bytes of total memory.
 In order to avoid this we go for the concept of DYNAMIC MEMORY
ALLOCATION.
 Allocation memory at run-time is called as dynamic memory allocation
 OPERATORS USED FOR DYNAMIC MEMORY ALLOCATION ARE:
 new
 delete

 “new” operator is used to allocate memory at run-time

 Syntax for new operator is:


datatype *pointer_variable = new datatype[size];

 “delete” operator is used to de-allocate memory at run-time.


31
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

Syntax for delete operator is:


delete[size] pointer_variable;

PROGRAM FOR DYNAMIC MEMORY ALLOCATION

#include<iostream>
using namespace std;
main()
{
int size,i;
cout<<"enter array size";
cin>>size;

int *p = new int[5];

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

 ‘p’ acts as a constant pointer


 It holds the address of memory allocated.
 Delete operator is used because to free memory that is allocated at run-time.
 If we don’t use delete then that particular memory space cannot be used by other
variables.
 Both in compile-time and run-time memory allocation after closing program memory
is cleared.

In compile time allocation memory is automatically cleared, where as in run-time


allocation memory should be cleared by using “delete” operator.

32
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

CONSTANT OBJECTS AND CONSTANT MEMBER


FUNCTIONS

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

Program to demonstrate const object and 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;
}

vois show() const


{
cout<<x;
33
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

cout<<y;
}

void display()
{
cout<<"hello";
}
};

main()
{
demo d1;
const demo d2(20,40);
d1.show();
d2.show();
d1.display();
d2.display();// error
}

STREAMS

 A stream is a sequence of bytes.


 It acts like a source from which data can be accepted.
 Sometimes it acts like a source to which data can be sent
 A stream that provides data to program is INPUT STREAM.
 A stream that receives output from program is called OUTPUT STREAM.
 Standard input stream
 The default input device is the KEY BOARD.
 Standard input stream accepts input from key board.
 It uses an object “cin” and an overloaded operator ”>>” for accepting data from
input device.
 Syntax for standard input stream is:
cin >> variable;

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.

 Standard output stream


 Default output device is the computer’s screen.
 Standard output streams uses an object called as “cout” and “<<” operator to
display values or data.
 Syntax for output stream is:
cout<<variable;
cout<<a<<b<<c;
 Using << to print multiple values as shown above is known as CASCADING.

PROGRAM TO DEMONSTRATE THE USE OF INPUT AND OUTPUT STREAMS

#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

 One class using the properties of another class is called as INHERITANCE.


 Main concept of inheritance is CODE REUSABILITY.
 The class whose properties are used by other class is called as BASE CLASS.
 The class which uses the properties of another class is called as DERIVED CLASS.
 Types of inheritance based on access specifiers:
 PUBLIC INHERITANCE
 PRIVATE INHERITANCE
 PROTECTED 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.

Example for inheritance

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

Program for single 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();
}

Program for multi-level inheritance

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

Program for hierarchical inheritance

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

Program for multiple inheritance

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

Program for hybrid inheritance

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

Class D:public B, public C


{
Public:
Void display4()
{
Cout<<”bye”;
} };

main()
{
D d1;
d1.display1();
d1.display2();
d1.display3();
d1.display4();
}

Single inheritance using private access specifier

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

 Program to demonstrate function overriding


#include<iostream>
using namespace std;
class one
{
public:
void show()
{
cout<<"base class";
} };
class two:public one
{
public:
void show()
{
cout<<"derived class";
} };
main()
{
two t;
t.show();
t.show();
}
 In the above program both functions calls in main() will call the derived class
function only, and two times derived class is displayed on screen.
 It is not possible to access the members of derived class through base class
object.
 In the above program if object is created for base class, then it violates the
concept of inheritance.
 So in order to access members of derived class by a base class we have two
methods:-
1. Casting base class
44
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

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

bp=&d1; // base pointer points to derived object


bp->print(); //base calss print() is called
(derived *) bp->print(); // derived calls 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
}

PURE VIRTUAL FUNCTION

 Pure virtual function is a function with no body or structure or definition.


46
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

 A pure virtual function will always be equals to zero in its declaration.


 This declaration is used to tell to the compiler that a function will be pure that is it
will not have any structure.
 A class containing at least one pure virtual function is said to be an abstract base
class.

#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

 Destructor is executed whenever an object is destroyed or terminated.


47
C++ NOTES
Prepared By: P.KARTHIK
Asst.Prof. ITD, MVSREC

 This means all clean up


( memory cleaning) and other final steps of class destruction are to be done in
destructor
 A virtual function will help the derived class in overriding the functionality of base
class
 Order of execution of destructors in inheritance is:
 Derived class destructor
 Base class destructor
 Consider the following program:

#include<iostream>
using namespace std;
class base
{
public:
base()
{
cout<<"base class created";
}
~base()
{
cout<<"base class destroyed";
}
};

class derived:public base


{
public:
derived()
{
cout<<"derived class created";
}

~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

 Compiler takes the statement


base *bp = new derived();
as:
base *bp;
derived d;
bp=&d;
 base *bp = new derived();
is run time memory allocation
the above 3 steps are compile time memory allocation.

STATIC VARIABLES AND STATIC MEMBER FUNCTIONS

 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

Static member functions

 Member functions may also be declared as static.


 There are several restrictions placed on static member functions.
 They may only directly refer to other static members of the class. (Of course, global
functions and data may be accessed by static member functions.)
 A static member function does not have a ‘this’ pointer.
 A static member function may not be ‘virtual’.
 They cannot be declared as const.

Consider the following program

#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

C++ Standard Exceptions:


C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below:

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

This is an exception thrown when a mathematically invalid


std::domain_error
domain is used
std::invalid_argument This is thrown due to invalid arguments.
std::length_error This is thrown when a too big std::string is created
This can be thrown by the at method from for example a
std::out_of_range
std::vector and std::bitset<>::operator[]().
An exception that theoretically can not be detected by
std::runtime_error
reading the code.
std::overflow_error This is thrown if a mathematical overflow occurs.
This is occured when you try to store a value which is out of
std::range_error
range.
std::underflow_error This is thrown if a mathematical underflow occurs.

54

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy