C++
C++ Programming language |
Moving From C to C++
C C++
printf() / scanf() cout<< / cin>>
Insertion Extraction
Op. Op.
Data type---------------------------------------------------à>>>same
Cont. statement------------------------------------------à>>>same
If / switch --------------------------------------------------à>>>same
Operators--------------------------------------------------à>>>same
Loop---------------------------------------------------------à>>>same
Array--------------------------------------------------------à>>>same
String-------------------------------------------------------à>>>same
Function---------------------------------------------------à>>>same+Advance
OOPs Concept
In PO programs the data is freely moving around the system and due to which there are chances of problem in system. So this problem is overcome by OO programs. OO concepts says it think about data and bind that data and methods those are manipulating that data into one entity known as object and then utilize that object into system.
Example: C++, Java, C#, VB.Net etc.
There are some fundamental concepts of OO Language which a language has to
follow to be a truly OO language.
• OBJECT
• CLASS
• ABSTRACTION
• ENCAPSULATION
• DATA HIDING / INFORMATION HIDING
• INHERITANCE
• POLYMORPHISM
• CLASS
• ABSTRACTION
• ENCAPSULATION
• DATA HIDING / INFORMATION HIDING
• INHERITANCE
• POLYMORPHISM
Lets take a brief look into these concepts.
Objects: Object represent real world entity into a program. for example an
employee which is real world entity we can make an object of it and then utilize it in
a program with its behaviors and actions.
Some other common definitions
1. Object is an instance of a class.
2. Object is a variable of user defined type / abstract data type.
a program with its behaviors and actions.
Some other common definitions
1. Object is an instance of a class.
2. Object is a variable of user defined type / abstract data type.
Class:
Class represent template for an object. It actually contains data and there behavior / methods in it and for utilization of it we need to create an object of that particular class. we can create number of object with one class. Some other common definitions
1. A collection of data and code to handle that data.
1. A collection of data and code to handle that data.
2. Class is a user defined type / abstract data type.
3. Class defines basic layout and functionality of an object.
Oops Property:
abstraction.
Some other common definitions
1. Abstraction is a process of mimicking a behavior.
2. Simplifying complex reality by modeling classes appropriate to problem.
3. Abstraction is a process that involves identifying the crucial behavior of an object
and eliminating irrelevant and tedious details.
Some other common definitions
1. Abstraction is a process of mimicking a behavior.
2. Simplifying complex reality by modeling classes appropriate to problem.
3. Abstraction is a process that involves identifying the crucial behavior of an object
and eliminating irrelevant and tedious details.
Encapsulation:
Binding the data and code to access that data. Encapsulation only refers to a container which has a data and its related functions in it. Some other common definitions
1. When an objects state and behavior are kept together they are encapsulated. The
data and the methods that manipulated that data are stored together in cohesive
unit.
Data Hiding / Information Hiding:
As encapsulation bind data and methods
together, data hiding restrict sensitive data accessing to the system. It is also achieved by using access modifiers i.e. Private, Protected and Public. In Figure 1 you can see in class Employee that there are notations minus(-) and Plus(+) they represents access modifier, minus sign restrict access outside the class and plus sign gives access outside the class. Some other common definitions
1. Insulation of data from direct access by the program.
Polymorphism:
It means we can declare one or more meaning of one world or operator. We can also redefine the meaning of operator. It includes function overloading, operator overloading, virtual function, virtual base class etc.
Inheritance:
Defining new classes from the existing one. The new class will get all the methods and properties of the existing class. The new class known as sub class / child class / derived class. The existing class known as super class / parent class / base class. Inheritance is implied by “is-a” or “kind-of” relationship. Inheritance is basically used for reuse the code and focus to make generic kind of thing rather than specific one. Some other common definitions
1. An object can acquire the properties of another object.
1. An object can acquire the properties of another object.
Input output function:
cout :- It is output stream used to print message. Message specify within quotation mark. It print in same line. To print in different line, we use ‘\n’ or endl.
Eg,
cout<<”Hello”;
cout<<”c++”;
O/P
Helloc++
To print in different line we use \n or endl.
cout <<”Hello\nc++”;
Or
cout<<”Hello”<<endl;
cout<<”c++”;
O/P Hello c++
Data type :-
- int –Also Called short / signed int, space 2 byte, range is 215 to 215-1
- long – space is 4 byte, Range 231 to 231-1
- float – Space is 4 byte, Range is 1038
- double – Space is 8 byte, Range is 10308
- long double – Space is10 byte, Range is10380
- char– Space 1 Byte.
int – 2 byte → 215 + 215 – 32768 to 32767
Manipulator:
To use manipulator we use iomanip.h header file.
setw (no.) –
Set minimum no. of digit.
int a = 65
cout<<setw(5)<<a;
_ _ _65
a = 65
setprecision :-
It is used to set no. of decimal places.
float a = 5.5;
cout<<a;
o/p 5.500000
cout<<setprecision (2)<<a;
o/p 5.50
oct -
print decimal into octal
Int a = 65;
cout <<oct <<a;
o/p 101
hex –
print decimal into hexadecimal
Int a=65;
cout<<hex<<a;
o/p 41
endl :-
for new line
fflash :-
Remove garbage collection memory from memory when we input value.
cin :-
It is input stream and used to input value from keyboard.
Eg
Write a program in c++ to find sum of two no.
#include<iostream.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr();
cout<<”enter two no.”;
cin>>a>>b;
c=a+b;
cout<<c;
getch();
}
Operators :-
(1) Arithmetic operator :- + , - , * , / , % (remainder)
% applicable only on integer(int and long).
priories.
* , / , % (decrease)
+, -
In case of same priority solve from left to right.
a/b/c a*b/c a/b*c
r/c r/c r/c
↓
r r r
Float a=5 & b = 10
c=1/2 x a x b here 1 and 2 are integer hence divisor of this is 0
0x5x10=0
c=axbx1/2
=25
{ expression result data type depend on available largest data type in expression not depend on storing variable.
Eg. int , long ,float , large }
Assignment operator (=):- It is used to assign value from Right to left.
a = 5 ; √
5 = a; x
a = b
a = bxc
bxc =a; x
Relation operator <,>,<=,>=, ==,!=
If(cond. )
{
processing
}
else
{
processing
}
eg.
int a =5
if (a=10)
cont<<”Hello”,
else
cout<<”buff”;
note: if we do not use any relational operator at conditional place then assume not equal zero condition.
Hence above condition become
If(10)
Hence assume as
if(10!=0) {!=→is not equal to}
O/P Hello
2 Logical operator :-
&&, ||,!
This are use to make on condition out of more than one condition.
Here && returns true when all condition are true otherwise return false.
||(or) return false when all condition are false otherwise return true.
!(not) used with one condition.
3. Conditional/ ternary operator :-
True |
If(a>b)
False |
else
C=b;
4. Bitwise operator;:-
&, |, ^ , ~, <<, >>
and (&) – 10&12 →1010 (binary conversion of 10)
1100 (binary conversion of 10)
1000
∟(8)
10 | 12 → 1010
1100
1110 (14)
10 ^12
1010
1100
0110 (6)
~25 → ~101
010 (2)
10<<3
1010 Shift value right to left by three digit
1010000
=80
Formula to calculate above..
If we use
a <<b then we calculate
a*2b
eg.
10x23
10 >> 3
1010
0001010
1
Formula is a/2b
Arithmetic assignment operators:-
+=, -=,\=,%=,*=
a = 5 a = 4
a =a+3 a *= 3
8
a += 3
↓
8 12
Increament/Decreament
i =4
i++ I--/--i
i++\++I 3
↓
5
Switch statement :-
switch (var)
{
case val
processing
break :
case val2;
processing;
break :
default :
processing
}
Loops :-
For | While | Do While |
For (initialize;condition; Incr/decr) | while { processing } | Do { processing } while(Cond); |
for(i=1;i<=10;i++) for (; ;) { processing } for(i=10;i<=0;i++); printf(“%d,i); o/p nothing | while(i<=10); { } while() { processing } i=10while(i<0) { printf(“%d”,j); i++ } } nothing | Do { processing } while(i<=10); do { processing } while(); x i=10 do { printf(“%d”); i++; } while(i<0); 10 |
Eg. Write a program in c++ to Print 1 to 10
#include<iostream.h>
#include<conio.h>
main()
{
for (i=1,i<=10;i++)
cout<<i<<” “;
getch();
}
Array :-
It is a linear collection of elements of similar data type values. Its size must be constant. Its size specifies in square bracket. Its index always start zero value can be initializes. It declaration time value specifies in curly brackets.
Int a [1000]
Int a [ ]; X
Int b = 10;
Int a[b]; X
const int b = 10;
Int a[b]; √
Int a[10] = {5,10,15,20,25…….}
Int a[.] = {5,10,15,…..20};
Read value in Array :-
for (i=0;i<10;i++)
cin>>a[i];
to print value in array
for (j=0 ; j<=10 ; j++)
cout<<a[ j];
Program
:-
#include<iostream.h>
#include<conio.h>
main()
{
int a[10], i;
clrscr();
cout<<”Enter Array Element”;
for (i=0;i<10;i++)
cin>>a[i];
for (i=0;i<10;i++)
cout <<a[i]<<” “;
getch();
}
Function :-
It is part of program in which we can perform any processing. It is used to define repeated processing. It can be define at above the main function and below the main function. It is execute only when we call it at main function. One UDF can call another UDF. If we define function at below of main function then its prototype must be define at variable declaration place. We define function using following syntax.
Return_type function_name(Parameter/argument)
{
processing
}
Parameter means sending value from calling place to define place, while return type means sending value from definition place to calling place. We can return only one value at a time, while parameter of zero, one or more. these may be of similar or dissimilar data type.
Function name must be user defined word.
Find sum of two no
# include <iostream.h>
# include <conio.h>
int sum (int a, int b)
{
int c ;
c= a + b;
return c;
}
main ()
{
int x, y, z;
clrscr ();
cin>> x>>y;
z =sum (x, y);// calling of sum function
cout <<z;
getch( );
}
when we call function number of parameter and data type and their sequence must be same.
When we return value by using return statement then return value data type, return data type, and store value (at calling place) data type must be same.
→ Find factorial of given
# include <iostream.h>
# include <conio.h>
int fact (int n)
{
int f =1 , i;
for (i=1 ;i<=n; i++)
f=f x i;
return f;
}
main()
{
int f, n;
cin >>n;
f=fact(n);
cout << f;
getch ();
}
→ Calculate value of N.C.R
# include <iostream.h>
# include <conio.h>
int fact (int n)
{
int f =1 , i;
for (i=1 ;i<=n; i++)
f=f x i;
return f;
}
main()
{
int f1, f2, f3, ncr, n, r;
cin >>n>>r;
f1=fact(n);
f2=fact(r);
f3=fact(n-r);
ncr=f1/(f2 x f3);
cout << ncr;
getch ();
}
print Fibonacci series
# include <iostream.h>
# include <conio.h>
void fib (int n)
{
int a = 0, b = 1
for (i=1; i<=n; i++)
{
cout<<a<<” “;
c= a+b;
a = b;
b=c;
}
}
main ()
{
fib (5);
}
Write a Program to check a number is prime number or not for given no.
#include<stdio.h>
#include<conio.h>
int prime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i= =0)
return 0;
}
return 1;
}
main()
{
int n;
clrscr();
cout<<”Enter No”;
cin>>n;
if(prime(n)= =1)
cout<<”Number is prime”;
else
cout<<”Number is not prime”;
}
O/P
Enter No 5
Number is prime
→ Default argument :-
→ Default argument :-
In this we can define with parameter which are optional. It means when we call the function need not to specify parameter value. It can be possible, When we initialize some default value at function definition time.
Eg.
# include <isotream.h>
# include <conio.h>
int sum (int a=1, int b=2)
{
return a+b;
}
main()
{
cout << sum ()<<endl;
cout << sum(10) <<endl;
cout << sum(10,8) <<endl;
getch ();
}
O/P
3
12
18
In this we can initialize all parameter. In this L → R 1st complsary than optional is possible while 1st optional than complsary this is not possible
Eg. Int sum (int a, int=4) √
sum (int a=1, int b) x
→ Function overloading:-
We can define two or more function with same name but they are must be different by the parameter in term of number of parameter or parameter data type or parameter data type sequence called function overloading.
When we call the function automatically call particular function according to parameter and get the result.
If any call function does not match with their parameter then generate error.
Eg
Calculate are of square, rectangle, circle and triangle as
# include <isotesm.h>
# include <conio.h>
int area (int x)
{
return x*x;
}
int area (int x , int y)
{
return x*y;
}
float area (float r)
{
return 3.14*r*r;
}
float area (float a, float b)
{
return 0.5*a*b;
}
main ()
{
float a ,b;
int x, y ;
cin >> a >> b;
cin >> x >> y;
cout << area (x)<<endl;
cout << area (a) <<endl;
cout << area (a, b) <<endl;
cout << area (x, y) <<endl;
getch ();
}
o/p
2 3
6 8
36
12.560000
3.000000
48
→ Intine function:-
A Simple function which follow inline keyword called inline function. A simple function which allocate different memory and when we call, control switch over from calling place to definition place and after completion again switch over at calling place. It waste the computer CPU time. To overcome this problem we use inline function. It doesn’t create its separate memory hence when we call it become itself at calling place.
Eg
Find sum of two No.
# include <iostream.h>
# include <conio.h>
inline int sum (int a, int b)
{
int = c + a;
return c ;
}
main ()
{
cout << sum (5,10);
getch ();
}
Note:
When we made inline function it work in call function memory and if we want to perform large calculation like we use loop then it generate warning. To overcome this problem . We can create outline (simple) function .
→ Template function ;-
Template is a class which is use to convert the data type. We create an object of template class type, which behave as variable data type. That means we store integer value then this variable become automatically of integer type. A function used a template class called template function.
It is generally we use when we perform same processing for different data type.
#include <iostream.h>
# include <conio.h>
template <class temp>
void swap (temp &a, temp &b)
{
temp c;
c=a ;a=b ;b=c;
}
main
{
int x ,y; float a, b;
cin >> x >> y;
cin >> a >> b;
swap (x, y);
swap (a, b);
cout << x << y;
cout << a << b;
getch ();
}
i/p
3 5
7 9
o/p
5 3
9 7
→ Class and object :-
Class is a place where we define some attribute such as data member or function member. In this we can use declaration but cannot use definition. This means we cannot perform any processing directly in class body. If we want to perform to processing then we use function. Class automatically does not create its memory when we define it. Class defines with class keyword and we this we specify tag name.
To create the memory of the of class we create an variable of class type called object. We can create one or more object for one class and create the separate memory for each member.
Eg.
# include <iostream.h>
# include <conio.h>
class first
{
int a, b, c;
public: //it define all below member of class are public.
void read ()
{
cin >> a >> b;
}
void sum ()
{
c = a + b;
}
void show ();
{
cout << c;
}
};
main()
{
first ob1;
ob1. read ();
ob1 . sum ();
ob1 .show ();
getch ();
}
I/P
5 20
O/P
25
# include <iostream.h>
# include <conio.h.>
class first
{
int a;
public :
void read (int x)
{
a = x ;
}
void show ()
{
cout << a<<endl;
}
};
main ()
{
first ob1, ob2, ob3;
ob1 . read (1);
ob2 . read (2);
ob3 . read (3);
ob1 show () ;
ob2 –show ();
ob3 – show ;
getch ();
}
O/P
1
2
3
Array of Object:-
In this we can create array of object. It just like simple array and it create memory at static memory allocation. Its size must be constant. It allocates contiguous memory allocation.
# include <iostream.h>
# include <conio.h.>
Class Array_demo
{
int a;
public :
void read ()
{
cin >> a;
}
void show ()
{
cout << a;
}
};
main ()
{
Array_demo ob1 [10];
int i ;
for (i=0; i<=10; i++);
ob1[i].read ();
for(i=0;i<10;i++)
ob1[i].show();
getch ();
}
→ Dynamic object :-
An object of class type is dynamic if it is declare as pointer object.
Pointer object doesn’t create memory automatically. We use new keyword to create memory in pointer object. In this without create memory we cannot access the class member. To excess member we use arrow (->) sign.
# include <iostream.h>
# include <conio.h.>
Class array_demo
{
int a;
public :
void read ();
{
cin >> a;
}
void show ()
{
cout << a<<endl;;
}
}
};
main ()
{
array_demo *ob1, *ob2, *ob3;
ob1 = new array demo ();
ob2 = ob1;
ob3 = new array_demo ();
ob1 → read ();
ob2 → read ();
ob3 → read ();
ob1 → show ();
ob2 → show ();
ob3 → show ();
}
}
I/P
1
2
3
O/P
2
2
3
Class complex
{
int a,ib1 , a2 ,ib2 ,a3 ,ib3;
public :
void read ()
{
cin >> a1 >> ib1;
cin >> a2 >> ib2;
}
void sum ()
{
a3 = a1 + a2;
ib3 = ib1 + ib2;
}
void show ()
{
cout << a3 << “+ i” << ib3;
}
};
main ()
{
complex *ob1;
ob1 = new complex ();
ob1 → read () ;
ob1 → sum ();
ob1 → show ();
}
I/P
2 4
5 6
O/P
7+i10
→ Passing parameter as object
# include <iostream.h>
# include <conio.h>
class distance
{
int f, in;
public :
void read ()
{
cin >> f >> in;
}
void sum (distance d1, distance d2)
{
f = d1.f + d2.f ;
in = d1. in + d2.in;
if (in >12)
{
f++ ;
in = in – 12;
}
}
void show ()
{
cout << f << in;
}
};
main ()
{
distance ob1; ob2; ob3;
ob1. read ();
ob2. read ();
ob3 . sum (ob1, ob2);
ob3 . show ();
}
I/P
2 4
5 6
O/P
7+i10
→ Find sum of two matrix
# include <iostream.h>
# include <conio.h>
class matrix
{
int a [3] [3] ;i ,j;
public:
void read ()
{
for (i=0; i<3; i++)
for (j =0 ; j<3; j++)
cin >> a[i][j];
}
void sum (matrix m1, matrix m2)
{
for (i=0; i<3; i++)
for (j =0 ; j<3; j++)
a[i][j] = m1.a[i][j] +m2.a[i][j];
}
void show ();
{
for (i=0; i<3; i++)
{
for (i =0 ; j<3; j++)
cout << a[i][j] <<” ”;
cout << endl ;
}
};
main()
{
matrix ob1, ob2, ob3;
ob1 . read ();
ob2 . read ();
ob3 . sum (ob1, ob2) ;
ob3 show ();
}
In C++ we can pass parameter in function which may be class type object and this object pass just like primary data type variable that means object can be pass by value or by address method. In above example an object pass by value method.
Returning object from function :-
Using this mechanism we can return an object of class it just like return the simple variable by using return statement. But it return single object only
→ Find sum of two matrix
# include <iostream.h>
# Include <conio,h>
class matrix
{
int a[3][3],I,j;
public:
void read ()
{
for (i=0; i<3; i++)
for (i = 0 ; j<3; j++)
cin >> a[i][j];
}
matrix sum (matrix ob2)
{
matrix t;
for (i=0; i<3; i++)
for (j =0 ; j<3; j++)
t.a [i][i] =a[i][i] +ob2 .a[i][i];
return t;
}
void show ()
{
for (i=0; i<3; i++)
{
for (i =0 ; j<3; j++)
cout << a[i][j]<<” ”;
cout << endl;
}
}
};
main ()
{
matrix ob1, ob2, ob3;
ob1 . read ();
ob2 . read ();
ob3 = ob1 sum (ob2):
ob3 show ();
}
→ Findsum of two complex No.
# include <iostream.h>
# include <conio.h>
{
int a; ib;
public:
void read ()
{
cin >> a >>: ib;
}
complex sum (complex ;d)
{
complex t;
t. a = a +d.a;
t+ ib =ib +d.ib;
return t;
}
void show ();
{
cout << a << ib ;
}
};
.main ()
{
complex ob1, ob2, ob3;
ob1 read ()
ob2 read ()
ob3 = ob1.sum(ob2);//---------------
ob3 show .()
getch();
}
---------------Call sum function with respect of ob1 and with parameter ob2 and store return value into ob3.
Sum function is compare as follows
int sum (int )
That means sum is a function which has a parameter of class type object and return value of class type object
Eg. Find sum of two Matrix using above method. Here we define function outside the class.
# include <iostream.h.
# include <conio.h>
class matrix
{
int . a[3][3],i,j;
public :
void read ();
matrix sum (matrix);
void show ()
};
void matrix : : read ()
{
for (i=0; i<3; i++)
for (i =0 ; j<3; j++)
cin >> a[i][j];
}
matrix matrix : : sum (matrix .d)
{
matrix .t;
for (i=0; i<3; i++)
for (j =0 ; j<3; j++)
t. a [i][j] = a[i][j] +d .a[i][j]:
return t:
}
void matrix : : show()
{
for (i=0; i<3; i++)
{
for (j =0 ; j<3; j++)
cout << a[i][j] << “ “;
cout << \n”;
}
}
main ()
{
matrix ob1 ;[10] ;
int i ;
for (i=0; i<10; i++)
ob1 [i] . read ();
s = ob1[10] (sum ob1[i]);
for (j =0 ; j<10; j++)
s = s. sum(ob1 [i])
s.show ();
}
Constructor :-
It is like simple function which name match with class name called constructor.
It following property :-
(1). It don’t return any value hence it does not have any return type.
(2). It is automatically call when we create memory of object.
(3). In this we can pas paremeter hence it can be overload.
(4). It is calls the respect of every object for which we create the memory
(5). One object can call one constructor at a time.
(6). One constructor can be call again and again with reference of different different object.
(7). Constructor is used to construct the memory of the object.
When we create on object of class always call constructor if we do not made user define constructor then it call built in constructor but once we made user defined constructor object calls only that if not match then generate error.
Eg
# include <iostream.h>
# include <conio.h>
class first
{
int a;
public ;
first ()
{
a= 1;
}
void show()
{
cout << a;
}
};
main ()
{
first ob1
ob1. show ();
}
o/p → 1
# include <iostream.h>
# include <conio.h>
class first
{
int a;
public :
first ()
{
a =1;
}
void show ()
{
cout << a<<endl;
}
first (int x)
{
a = x ;
}
first (int x, int y )
{
a = x + y;
}
};
main ()
{
first ob1 ,ob2(2), ob3(4,5);
ob.show ();
ob2.show ();
ob3.how ();
getch ();
}
O/P
1
2
9
# include <iostream.h>
# include <conio.h >
class first
{
int a, b
first ()
{
a = 1;
b = 2;
}
public:
first (int x ,int y)
{
a = x;
b = y;
}
void show ()
{
cout << (a + b);
}
};
main ()
{
first ob1, ob(3,4);
ob1 .show ();
ob2 .show ();
}
O/P
Generate Compile Time error for calling constructor with respect of ob1.
→ Default constructor :-
In this we can initialize some default value of constructor parameter. Hence if we do not specify value with the object then it takes default value.
Eg.
# include <iostream.h>
# include <conio.h>
class first
{
int a, b;
public:
first(int x=1,int y=2)
{
a = x;
b = y;
}
void show ()
{
cout << (a + b)<<endl;
}
};
main ()
{
first ob1, ob2(3,4);
ob1. show ();
ob2 show ();
}
O/P
3
7
→ Copy constructor :-
A constructor which has paremeter of class type object called copy constructor. In this object must be passed by returns method to amphipod to copy constructor we do a simple constructor which may be or without partimeteised
Or parimetered constructor
# include <istream.h>
# include <conio.h>
class first
{
int a;
public:
first ()
{
a = 2
}
first ( first &d)
{
a = d. a* d.a
}
void show ()
{
cout << a<<endl;
}
};
main ()
{
first ob1
first ob2 = ob1; // first (ob1);
ob1.show ()
ob2.show ()
}
O/P
2
4
Destructor:-
Constructor is used to create memory while destructor is used to destroyed memory. It is like constructor followed by tilled sign (~). It execute when program is end. In this we don’t pass any paremeter hence it can’t be overload. It calls with respect of each object when object memory is destroyed. In a class we can have zero or more construct but only one destructor can exist. Destructor calling sequence is reverse then constructor calling sequence. All constructor or destructor can be public or private.
class first
{
int a;
public:
first (int x)
{
a = x;
cout << a<<endl;
}
~ first ()
{
cout << a;
}
};
main ()
{
first ob1 (2);
}
o/p
2
2
# include <iostream.h>
# include <conio.h.
class first
{
int a;
public :
first (int x)
{
a = x;
count << a;
}
~ first ()
{
cout << a;
}
};
main ()
{
first ob(1), ob2(2), ob3(3);
}
o/p
1 2 3
3 2 1
Operator overloading :-
It means we can define one or more meaning of an operator which are already define called operator overloading.
It can be possible by using this mechanism. We can overload any operator except following four operator .
1. pointer sign (*)
2. Access Operator(Dot) .
3. Access Operator(Arrow) ->
4. Resolution Operator ::
relation op
Operator broadly are divided into three part.
1. Unary (++, -- , ~ ,!, +, - (sign operator))
2. Binary (+ ,-,* etc.)
3. Trinay ( ? : ) .
When we want to overload any operator, we make a function which name is operator symbol with operator keyword. According to type of operator, we have some rule to make this.
Unary operator overloading :-
In this we use any unary operators and it doesn’t have return type that means it doesn’t return any value and we can’t pass any parameter of class type object.
Eg. Get Next Value Using unary Operator Overloading
# include<iostream.h>
# include<conio.h>
Class first
{
int a;
public;
first()
{
a=1;
}
void operator ++()
{
a++;
}
void show()
{
cout<<a;
}
};
main()
{
first.ob1;
ob1++;//call operator ++ function with respect of ob1
ob1.show
getch()
}
O/P
2
Get next date :-
# include<iostream.h>
# include<conio.h>
class date
{
int d,m, mon[13],y;
public;
date()
{
cin>>d>>m>>y
mon[1]=mon[3]=mon[5]=mon[7]=mon[8]=mon[10]=mon[12]=31;
mon[4]=mon[6]=mon[9]=mon[11]=30;
if (y%4= =0 && y%100!=0 || y%400= =0)
mon[2]=29;
else
mon[2]=28;
}
void operator ++( )
{
d++;
if(d>mon[m])
{
d=1;
m++;
}
if(m>12)
{
m=1;
y++;
}
}
void show( )
{
cout<<d<<”/”<<m<<”/”<<y;
}
};
main( )
{
clrscr( )
cout<<”enter date”;
date ob1;
ob1++;
ob1.show();
getch( );
}
I/P
28 2 2009
O/P
1/3/2009
Binary operator overloading :-
In this we can overload any binary operator and in this overloading we follow following condition.
We can pass parameter of class type object and we can also return but notice that we can’t pass more than one parameter. In this we can overload only binary operators.
Eg. Find sum of two complex no
# include<iostream.h>
# include<conio.h>
class complex
{
int a,ib;
public;
void read( )
{
cin>>a>>ib;
}
complex operator +(complex d)
{
complex t;
t.a=a+d.a
t.ib=ib+d.ib;
return t;
}
void show( )
{
cout<<a<<”+i”<<ib;
}
};
main( )
{
complex ob1,ob2,ob3
ob1.read( );
ob2.read( );
ob3.read=ob1+ob2;
ob3.show( )
}
String Concentruction :-
# include<string.h>
# include<iostream.h>
# include<conio.h>
class string
{
char a[50]
public;
void read
{
cin>>a;
}
string operator t(string d)
{
string t;
strcpy(t.d,a);
strcat(t.a,d.a);
return t;
}
void show( )
{
cout<<a;
}
};
main()
{
string ob1,ob2,ob3
ob1.read( );
ob2.read( );
ob3=ob1+ob2
ob3.show( );
}
String Copy using Assignment Operator overloading
# include<string.h>
# include<iostream.h>
# include<conio.h>
class string
{
char a[50]
public;
void read( )
{
cin>>a;
}
void operator=(string d)
{
strcpy(a, d.a)
}
void show( )
{
cout<<a;
}
};
main( )
{
number ob1,ob2,ob3
ob1.read( )
ob2=ob1;
ob2.show( )
}
Type Casting :-
1. Primary Datatype to object data type:
In this mechanism we can store primary data type variable value into object. It can be possible by simply overload assignment operator with primary parameter.
# include<iostream.h>
# include<conio.h>
class abc
{
int a;
float b;
public;
void show( )
{
cout<<a<<b;
}
void operator =(int x)
{
a=x;
}
void operator =(float y)
{
b=y;
}
};
main( )
{
abc ob1;
int x; float y;
cin>>x>>y;
ob1=x; //call operator = with int parameter
ob1=y;
ob1.show();
}
I/P
2
3.2
O/P
2 3.2
Object to primary data type :-
In this we can store any object into primary data type variable and it can be possible simply overload the data type keyword (int, float etc) with operator keyword. It calls with respect of object according to stored variable data type.
# include<iostream.h>
# include<conio.h>
{
int a;
float b;
public;
void read( )
{
cin>>a>>b;
}
operator float( )
{
return b;
}
};
main( )
{
abc ob1;
int x;
float y;
ob1.read( );
x=ob1; // call operator int with respect of ob1
y=ob1;
cout<<x<<y;
}
I/P
2
3.2
O/P
2 3.2
Object data type to object data type :-
In this we can store one class object into another. In this define a class and we can simply overload class name with operator keyword into another class. In this we can convert one class object to another class object but can’t convert vice versa. if we want convert than we must define both operation in both class.
# include<iostream.h>
# include<conio.h>
class farn
{
float f;
public;
farn(int c)
{
f=1.8xc+32
}
void show( )
{
cout<<t;
}
};
class cent
{
int c;
public;
void read()
{
cin>>c;
}
operator farn( )
{
farn ob1( c)
return ob1;
}
};
main( )
{
farn ob1(1)
centr ob2
ob2.read( );
ob1=ob2; //call operator farn with respect of ob2
ob1.show( );
getch();
}
Decimal to binary & Binary to Decimal :-
# include<iostream.h>
# include<conio.h>
# include<maths.h>
class deci;
class bina
{
int b,s;
public;
bina(int);
void read( );
void show( );
operator deci( );
};
class deci
(
int d,s;
public:
deci(int d1)
{
int b,z=0;
s=0;
while (d1!=0)
{
b = d1%10;
d1 = d1/10;
s = s + b*pow(2,z);
z++;
}
}
void read( )
{
cin>>d;
}
void show ( )
{
cout<<s;
}
operator bina( )
{
bina t(d);
return t;
}
}
bina::bina(int d)
{
int b, z=0;
s=0;
While(d!=0)
{
b=d%2;
d=d/2;
s=s+b*pow(10,z);
z++;
}
}
void bina::read( )
{
cin>>b;
}
void.bina::show( )
{
cout<<s;
}
bina::operator deci( )
{
deci t(b);
return t;
}
void main( )
{
clrscr( );
bina ob1(1);
deci ob2(1);
cout<<”Enter No in Decimal”;
ob1.read();
ob2=ob1;
cout<<”Binary Equilent “;
ob2.show()
cout<<”\nEnter No in Binary”;
ob2.read()
ob1=ob2;
cout<<”Decimal Equilent “;
ob1.show();
getch();
}
Inheritance:-
In this mechanism we can inherit one class into another class. That means we can use one class member into another without create object and without rewrite program code. It can be possible by simply first class name specify with the second class definition. We use public, private, protected keyword, separated by colon to inherit first class. First class is called base class while second class is called derived class. Base class member can be use in derived class if they are public or protected, can’t use private member. When we create an object of derived class we can create memory of both base and derived class. We can access member for both base class and derived class.
Find sum of two on.
# include<iostream.h>
# include<conio.h>
class number
{
int a,b;
public:
void read();
{
cin>>a>>b;
}
};
class result : public number //this is inheritance, here number is base class
{ // while result is derived class.
int t;
public:
void sum()
{
c=a+b;
}
void show()
{
cout<<c;
}
};
main()
{
result ob1;
ob1.read();
ob1.sum();
ob1.show();
}
Member Specifier :-
(1) private :- These member can be access by any member of class within class body but can’t access outside the class though its derived class.
(2) protected :- These member can be use by an member within class body and we can also access in derived class but can’t use other class body or main function.
(3) public :- These member can be access anywhere either in class, derived class and out side class by any member of class.
Generally all function member are defined as public while other data member are private. This is not a rule.
#include<iostream.h>
#include<conio.h>
class first
{
private: int pri;
protected: int pro;
public: int pub;
void read()
{
pri=1; √
pro=2; √
pub=3; √
}
};
class second : public first
{
public:
void show()
{
cout<<pri;
cout<<pro; √
cout<<pub; √
}
};
main()
{
second ob;
ob.read(); √
cout<<ob.pri;
cout<<ob.pro;
cout<<ob.pub; √
}
Method of inheritance :-
(1) Public inheritance :- In this base class member other protected or public doesn’t change their original modifier. It means it behaves protected as protected and public member behave as public.
#include<iostream.h>
#include<conio.h>
class first
{
private: int pri;
protected: int pro;
public: int pub;
void read()
{
pri=1; √
pro=2; √
pub=3; √
}
};
class second : public first
{
public:
void show()
{
cout<<pri;
cout<<pro; √
cout<<pub; √
}
};
main()
{
second ob;
ob.read(); √
cout<<ob.pri;
cout<<ob.pro;
cout<<ob.pub; √
}
(2) Proctected Inheritance :- In this inheritance protected member doesn’t change their modifier while public member become protected hence using the derived class object we can’t access base class member at other place like main function but can access in further derived class.
#include<iostream.h>
#include<conio.h>
class first
{
private: int pri;
protected: int pro;
public: int pub;
void read()
{
pri=1; √
pro=2; √
pub=3; √
}
};
class second : protected first
{
public:
void show()
{
cout<<pri;
cout<<pro; √
cout<<pub; √
}
};
class third : public first
{
public:
void show()
{
cout<<pri;
cout<<pro; √
cout<<pub; √
}
};
main()
{
second ob;
ob.read();
cout<<ob.pri;
cout<<ob.pro;
cout<<ob.pub;
ob.show(); √
}
(3) Private Inheritance :- All member are of base class become private into derived class hence they can’t access further which may be further derived class or main function or outside class.
#include<iostream.h>
#include<conio.h>
class first
{
private: int pri;
protected: int pro;
public: int pub;
void read()
{
pri=1; √
pro=2; √
pub=3; √
}
};
class second : private first
{
public:
void show()
{
cout<<pri;
cout<<pro; √
cout<<pub; √
}
};
class third : public first
{
public:
void show()
{
cout<<pri;
cout<<pro;
cout<<pub;
}
};
main()
{
second ob;
ob.read();
cout<<ob.pri;
cout<<ob.pro;
cout<<ob.pub;
}
Types of Inheritance :-
(1)
A |
B |
(2)
A |
B |
C |
(3) Multiple inheritance
A |
B |
C |
D |
(4)
D3 |
D2 |
D1 |
A |
(5)
B |
C |
A |
D |
(6) Multipath inheritance
B |
C |
A |
D |
Single Inheritance:
It is like first example in which we make one base class and one derived class.
A |
B |
C |
In this inheritance we define one base class and one derived class. This derived class can also be parent (base) class of another derived class.
In above diagram…..
Member of class A can be used into class B, if they are protected or public and similarly member of class B can be used into class C hence we can use both member of class A and class B into class C member. We can create memory of all class using object of class c. Member of class A can be used into C, it is depends on inheritance of class A into Class B.
Ex :-
# include<iostream.h>
# include<conio.h>
class number
{
protected:
int a, b;
public:
void read()
{
cin>>a>>b;
}
};
class sum : public number
{
protected: int c;
public:
void add()
{
c=a+b;
}
};
class result : public sum
{
public:
void show()
{
cout<<c;
}
};
main()
{
result ob1;
ob1.read()
ob1.add()
ob1.show()
}
I/P
5 10
O/P
15
Multiple inheritance :-
A |
B |
C |
D |
In this inheritance we can make two or more base class and we can create one derived class for all base classes. All base class must have unique member if they are public or protected. These classes are not interlink together but all these classes are inherit into one derived class. Hence duplicate member can’t used into derived class. Hence duplicate name of either member function or data member doesn’t allow.
Eg.
# include<iostream.h>
# include<conio.h>
class number1
{
protected:
int a;
public:
void read()
{
cin>>a
}
};
class number2
{
protected:
int b;
public:
void read()
{
cin>>b;
}
};
class result : public number1, public number2
{
public:
void show()
{
cout<<(a+b);
}
};
main()
{
result ob1;
ob.1 read();
ob1.read();
ob1.show();
}
Hierarchical :-
D3 |
D2 |
D1 |
A |
In this inheritance we make one base class and its two or more derived class. With the respect of every derived class, parent class creates memory separately. All derived class are not inter link together. Hence they can have duplicate member. To use every derived class we use or create object of every derived class and this object create memory of derived and parent class only, It do not create memory of sibling class or other.
Eg.
# include<iostream.h>
# include<conio.h>
class number
{
protected:
int a;
public:
void read()
{
cin>>a
}
};
class evenodd: public number
{
public:
void show()
{
If(a%c= = 0)
cout<<”Even”;
else
cout<<”Odd”;
}
};
class prime: public number
{
public:
void show()
{
for(int i=2; i<a; i++)
{
if(a%i= =0)
break;
}
if(a= = i)
cout<<”Prime”;
else
cout<<”Not Prime”;
}
};
main()
{
evenodd ob1;
cout<<”Enter No for Even Odd”;
ob1.read();
ob1.show();
prime ob2
cout<<”\nEnter No for Prime”;
ob2.read();
ob2 show();
}
I/P
Enter No for Even Odd 5
O/P
Odd
I/P
Enter No for Prime 5
O/P
Prime
Hybrid inheritance :-
B |
C |
A |
D |
In above example member of class A can be use in class B. But can not use in class C. Member of class B & C or member of class A & C are not interlink together but member of class A or class B or class C can be used into derived class D.
Eg.
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rollno; char nam[20];
public:
void read()
{
cin>>rollno>>nam;
}
};
class marks:public student
{
protected:
int m1,m2;
public:
void readm()
{
cin>>m1>>m2;
}
};
class sports
{
protected: int sp;
public:
void reads()
{
cin>>sp;
}
};
class result:public sports, public marks
{
public:
void show()
{
cout<<rollno<<" "<<nam<<endl;
cout<<m1<<" "<<m2<<" "<<sp<<endl;
}
};
main()
{
clrscr();
result ob;
ob.read();
ob.readm();
ob.reads();
ob.show();
getch();
}
Multipath inheritance:
B |
C |
A |
D |
In this member of class A can be use in class B and can use in class C. Member of class B & C are not interlink together but member of class A or class B or class C can be used into derived class D. class A has dual property that means we can use its member into class B or Class C but at a time we can use only one derived class.
It is also called virtual class inheritance.
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rollno; char nam[20];
public:
void read()
{
cin>>rollno>>nam;
}
};
class marks:public virtual student
{
protected:
int m1,m2;
public:
void readm()
{
cin>>m1>>m2;
}
};
class sports:public virtual student
{
protected: int sp;
public:
void reads()
{
cin>>sp;
}
};
class result:public sports, public marks
{
public:
void show()
{
cout<<rollno<<" "<<nam<<endl;
cout<<m1<<" "<<m2<<" "<<sp<<endl;
}
};
main()
{
clrscr();
result ob;
ob.read();
ob.readm();
ob.reads();
ob.show();
getch();
}
Constructor in Inheritance :-
When we create a object of derived class it creates memory for both base class and drive class and constructor also call for both class constructor calling sequence is derived class and then base class but execution sequence is base class then derived class.
# include <iostream.h>
# include<conio.h>
class A
{
public :
A()
{
cout<<”A”;
}
};
class B:public A
{
public:
b()
{
cout<<”B”;
}
};
class C:public B
{
public:
C()
{
cout<<”C”;
}
};
main()
{
C ob1:
}
O/P- A,B,C
Parameterized Constructor:-
In this we create an object of only derived class and base class inherit into derived class. Hence derived class, call base class constructor automatically and it call only without parameterize if we want to call parameterized constructor then must be call explicitly.
# include<iostream.h>
# include<conio.h>
class A
{
int x;
public:
a(int y)
{
x=y;
cout<<x;
}
};
class B : public A
{
public:
b(int y):A(y) //explicit call of base class parameterized constructor
{
cout<<y;
}
};
main()
{
B ob1(4);
getch();
}
O/P 44
Constructor in Multiple inheritance :-
# include<iostream.h>
# include<conio.h>
class A
{
A()
{
cout<<”A”;
}
};
class B
{
public:
B()
{
cout<<”B”;
}
};
class C
{
public:
C ()
{
cout<<”C”;
}
};
class D: public B,A,C
{
public:
D()
{
cout<<”D”;
}
};
main()
{
D ob1;
getch();
}
O/P- BACD
//Constructor call according to specify sequence of base class with derived class D.
Friend function :-
A simple function which defined outside class which is not a member of class but it’s prototype define within class with friend keyword called friend function. Friend function can be call public, private, protected member of a class by using object of that class. And a function can be friend for one or more class at a time. When we call the friend function we don’t specify any object reference.
In following program void swap() is a simple function like main function but it call all member of class first because its prototype defined in class with friend keyword.
# include<iostream.h>
# include<conio.h>
class first
{
int a;
public:
void read()
{
cin>>a;
}
protected:
void show()
{
cout<<a;
}
// swap is a function which is friend of class first. |
};
class second
{
int b;
public:
void read()
{
cin>>b;
}
protected:
void show()
{
cout<<b;
}
// swap is a function which is friend of class second. |
};
void swap()
{
first ob1;
second ob2;
ob2.read();
ob1.read();
int t=ob1.a;
ob1.a=ob2.b;
ob2,b=t;
ob1.show();
ob2.show();
}
void main()
{
swap();
getch();
}
I/P
5 6
O/P
6 5
Friend class:-
A class can be friend with another that means we can use one class member into another but can’t use wise versa.
Like friend function class name define in first class with friend keyword hence we can use all public private protected member of class first into class second.
# include<iostream.h>
# include<conio.h>
class first
{
int a;
Public:
void read()
{
cin>>a;
}
Protected:
void show()
{
cout<<a;
}
// class second is a friend of class first. |
};
class second
{
public:
void read()
{
first ob;
ob1.read();
ob1.show();
}
};
main()
{
second ob1;
ob1.read();
}
Virtual function :-
A simple function followed by virtual keyword within class body called virtual function. It is used in method (function) overloading. In this we can define same function in base and derived class which is of same name, same parameter and same return type called method overloading. That means, base class method override on child class method and if we create an object of either base class or derived class call only base class function.
# include<iostream.h>
# include<conio.h>
class father
{
void show()
{
cout<<”Father”<<endl;
}
};
class child: public father
{
void show()
{
cout<<”Child”;
}
};
main()
{
father *ob;
ob = new father()
ob->show();
ob = new child()
ob->show();
}
O/P
Father
Father
In above example, father class show method override on child class method. To remove this problem we make virtual function in base class. Here we use virtual keyword with function definition in base class. Virtual is used to differentiate between these function.
# include<iostream.h>
# include<conio.h>
class father
{
public:
virtual void show()
{
cout<<”father”;
}
};
class child:public father
{
public:
void show()
{
cout<<”child”;
}
};
main()
{
father*ob1;
ob1-new father();
ob1.show();
ob1.new child()
ob1.show();
}
O/P
Father
Child
Pure virtual function:-
It is used to excess derived class member into base class or in other word base class member implement in derived class. Now base class is also called abstract class.
# include<iostream.h>
# include<conio.h>
class father
{
int a;
public:
virtual void show()=0;
virtual void read()
{
cin>>a;
show();
}
};
class child:public father
{
void show()
{
cout<<a;
}
};
main()
{
child ob1;
ob1.read();
}
I/P
6
O/P
6
File Handling:-
To perform the operation with the file we include a header file called fstream.h. File handling means store input output data permanently in the computer and can be store for reading or witting data. If we want to write data into file we create an object of ofstream class which is the derived class of fstream class. To perform input operation from file, create an object of ifstream class which is also derived class of fstream class. To perform input/output operation from file create an object of particular class type and we open then the file in given mode. These mode shows, what purpose to open the file in given mode such as reed data write data etc. These made are :-
Ios::out:- It is use create new file and if file already exist than overwrite it. All old data remove first then write new data. It is mostly used to open temporary file.
ios::app :- It is use create new file and if file already exist than add new data into file at then end of file. It is mostly used to open general working file.
ios::in :- It is used open in input mode to read data. If file doesn’t exit than generate error.
ios::binary :- It is used to open file in binary mode means we can perform operation and write data in binary format.
ios::truncate :- It is used to create file and old file is complete deleted from memory.
Eg.
Create file or write data into file.
# include<iostream.h>
# include<fstream.h>
# include<conio.h>
void main()
{
ofstream fout;
char nam[90];
int age;
fout.open(“navneet.cpp”, ios::app);
clrscr();
cin>>nam>>age;
fout<<nam<<” “<<age<<endl;
fout.close();
getch();
}
Display data from file :-
# include<iostream.h>
# include<conio.h>
# include<fstream.h>
void main()
{
ifstream fin;
char nam[90];
int age;
fin open(“navneet.cpp”);
flrscr();
while(!fin.eof())//loop works up-to end of file
{
fin>>nam>>age;
cout<<nam<<” “<<age<<endl;
}
fin.close();
getch();
}
Function use in File handling :-
(1) eof() :- It return true when file pointer is on end of file otherwise it return false. It is generally use when we input data from file.
(2) close :- It is used to close current open file. If we do not close then we can’t open again in same program.
(3) seekg :- It is used to move pointer on given position . In this we position specify in total number of byte to be move. This byte count from always top position.
(4) tellg :- It is used to get current position from top position in term total number of byte.
(5) get :- Input character by character from file.
(6) put :- It is used to print character by character into file.
(7) read :- It is used read record when we open the file in binary mode
(8) write:- it is used to write data into file in binary format..
(9) getline :- It is used to input signal line from the file or keyboard.
Eg.
Write data and create random access file.
# include<iostream.h>
# include<conio.h>
# include<fstream.h>
main()
{
fstream fout;
fout.open(“ooo.cpp”,ios::out I ios::in);
for(int i=1; i<=10: i++)
fout<<i;
fout.seekg(5);
fout<<”hello”;
fout.close();
getch();
}
Copy one file to another and count word, line, character and also print on output screen.
#Include<iostream.h>
# include<etype.h>
# include<fstream.h>
void main()
{
int c1=0 w=0, i=0;
fin.open(“fincpp.cpp”);
fout.open(“Hitesh.cpp”);
clrscr();
while(!fin.eof())
{
c=fin.get();
c=toupper( c);
c1++;
if(c==’ ‘ || c== ‘\n’)
w++;
if(.c== ‘\n’)
i++;
fout<<c;
cout<<c;
}
cout<<endl<<”Line=”<<i<<”; word=”<<w<<”,Char=<<c;
getch();
}
Exception Handling:
An exception is a special condition that interrupts the normal flow of program execution. There are a variety
of reasons why an exception may be generated (exceptions are typically said to be raised or thrown), by
hardware as well as software. Examples include arithmetical errors such as division by zero, underflow or
overflow, calling undefined instructions (such as attempting to invoke an unimplemented method), and
attempting to access a collection element out of bounds.
Objective-C’s exception support revolves around four compiler directives: @try, @catch, @throw, and
@finally:
■ Code that can potentially throw an exception is enclosed in a @try block.
■ A @catch() block contains exception-handling logic for exceptions thrown in a @try block. You can
have multiple @catch() blocks to catch different types of exception. (This is illustrated in “Catching
Different Types of Exception” (page 100).)
■ A @finally block contains code that must be executed whether an exception is thrown or not.
■ You use the @throw directive to throw an exception, which is essentially an Objective-C object. You
typically use an NSException object, but are not required to.
The example below depicts a simple exception-handling algorithm:
Cup *cup = [[Cup alloc] init];
@try {
[cup fill];
}
@catch (NSException *exception) {
NSLog(@"main: Caught %@: %@", [exception name], [exception reason]);
}
@finally {
[cup release];
}
0 comments:
Post a Comment