Professional Documents
Culture Documents
term
Object
Oriented
Programming
means
Introduction
C++ is an object-oriented programming language developed by
Bjarne Stroustrup at AT & T Bell Labs in the early 1980s.
Since the class concept was the major addition to the original C
language, it is called as "C with classes". However later in 1983, the
name was changed to C++. The idea of C++ comes from the 'C'
increment operator "++", there by suggesting that C++ is an
incremented version of 'C'. C++ is a superset of C. Therefore almost all
C programs are valid C++ programs.
Advantages of OOP
1. Object Oriented Approach
2. Closer to real world object
3. Dynamic Declaration
4. Data Security
5. Code Re-Usability & Extensibility
Object
An object is an instance (example or illustration) of a class. In
terms of variables, a class would be the data type and an object
would be the variable.
An object is a physical reality.
Inheritance
The mechanism of creating new classes by deriving the features
from existing classes is called Inheritance.
In OOP the concept of inheritance provides the idea of reusability &
extensibility. This means that we can add additional features of an
existing class without modifying it. This is possible by deriving a new
class from the existing one. The new class will have the combined
features of both the classes.
Encapsulation
Data Hiding
The process of hiding the data members and member functions
from access by the other class objects other than the same class
objects.
The data is not accessible to the outside world and only those
functions which are placed in the class can access it, these functions
provide the interface between objects data and the program. The
insulation of data from direct access by the program is called data
hiding.
Data Abstraction
It is the process of accessing the data members & member
functions with the objects.
Abstraction refers to the act of representing essential features without
including the background details and explanations. Classes use the
concept of abstraction and defined as a list of abstraction attributes.
Since the classes use the concept of data abstraction they are known
as Abstract Data Type (ADT).
Data Binding
Binding refers to the act of associating an object or a class with
its member. If we can call a method fn() on an object o of a class c, we
say that the object o is binded with the method fn(). This happens at
compile time and is known as static or compile - time binding.
-5The calls to the virtual member functions are resolved during runtime. This mechanism is known as dynamic binding. The most
prominent reason why a virtual function will be used is to have a
different functionality in the derived class. The difference between a
non-virtual member function and a virtual member function is the
non-virtual member functions are resolved at compile time.
Include files
Class declaration
Member functions definition
Main function
{
Local declaration;
Object declaration;
Executable coding;
}
-6member functions;
.
} object_names;
where class_name is a valid identifier for the class, object_names is an
optional list of names for objects of this class. The body of the
declaration can contain members, which can be either data or
function declarations, or optionally access specifiers.
All is very similar to the declaration on structures, except the new
thing called access specifier.
An access specifier is one of the following three keywords:
private, public or protected. These specifiers modify the access rights
that the members following them acquire:
-8function instead it copies the code from the inline function directly
into the calling function.
Inline is a hint to the compiler that you would like the function to be
inlined. The compiler is free to ignore the hint and make a real
function call.
this pointer:
"this" is a pointer that points the address of the current object.
The unique pointer is automatically passed to a member function
when it is called. The pointer "this" acts as an implicit argument to all
the member functions.
Object Arrays
We know that an array can be of any data type including struct;
similarly we can also have arrays of variables that are of the type
class. Such variables are called arrays of objects.
class employ
{
char name[10];
int age;
public:
void inputdata();
void outputdata();
};
ex:employ emp[5];
-9Create A Class With The Name Bank And Create An Array With 5
Cells And Accept Data And Print Data.
Example for an Object Arrays.
# include <stdio.h>
# include <iostream.h>
# include <conio.h>
class bank
{
int acno,cbal;
char cname[20];
public:
void input();
void output();
};
void bank::input()
{
cout<<"ENTER A/C NUMBER :";
cin>>acno;
cout<<"ENTER CUSTOMER NAME :";
cin>>cname;
cout<<"ENTER CURRENT BALANCE
:";
cin>>cbal;
}
void bank::output()
{
cout<<"ACCOUNT NUMBER IS
:"<<acno<<endl;
:"<<cbal<<endl;
- 10 }
void main()
{
int i;
bank b[5];
for(i=0;i<5;i++)
{
cout<<"ENTER VALUES FOR CELL :"<<i<<endl;
b[i].input();
}
clrscr();
for(i=0;i<5;i++)
{
cout<<"THE VALUES OF THE CELL
:"<<i<<endl;
b[i].output();
getch();
}
}
Stream
A stream is defined as a collection of pre-defined objects. The
iostream (Input/Output stream) defines the following two objects.
cout
cout
is
an
object,
defined
in
standard
output
- 11 -
<<
The operator << is called insertion or put to operator. It directs
the contents of the variable on its right to the object on its left.
Screen <----- cout <----- << <--- variable
e.g; screen<---cout<<"welcome";
cin
cin is an object, defined in standard input stream (istream). This
stream represents data coming from the keyboard. cin is an object of
istream with assign class, which is derived from istream class.
>>
This operator is called extraction or get from operator. It takes
the value from the stream on its left and places it in the variable on its
right.
Keyboard ---> cin ---> >> ---> variable
eg: keyboard-->cin>>x;
Reference Variable
A reference variable provides an alias (alternative name) for a
previously defined variable.
Syntax:
#include <stdio.h>
#include <conio.h>
# include <iostream.h>
void main()
{
int a=200;
int &b=a;
int &c=b;
clrscr();
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
cout<<"C VALUE IS :"<<c<<endl;
getch();
b=55;
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
cout<<"C VALUE IS :"<<c<<endl;
getch();
- 13 c=3500;
cout<<"A VALUE IS :"<<a<<endl;
cout<<"B VALUE IS :"<<b<<endl;
cout<<"C VALUE IS :"<<c<<endl;
getch();
}
Default Arguments
C++ allows calling a function without specifying all its
arguments. In such cases the function assigns a default value to the
parameter which does not have a matching argument in the function
call. We have to specify the default values when the function is
declared. The compiler looks at the prototype (declaration) to see how
many arguments the function uses and alerts the program for
possible default values. One important point is that only the trailing
arguments can have default values i.e. you must add default from
right to left. It is not possible to provide a default value to a particular
argument in the middle of the argument list.
Ex:
add (10,20,30);
add (10,20);
add (10);
add ();
- 14 # include <iostream.h>
# include <stdio.h>
# include <conio.h>
int add(int a,int b,int c=0,int d=0,int e=0)
{
return (a+b+c+d+e);
}
void main()
{
int m,n,p,q,r;
clrscr();
cout<<"ENTER ANY FIVE INTEGERS :"<<endl;
cin>>m>>n>>p>>q>>r;
cout<<"ADDITION OF 2 NUMBERS
ARE
:"<<add(m,n)<<endl;
allocated
memory.
Although
C++
supports
these
functions, it also defines two unary operators 'new' and 'delete' that
perform the task of allocating and freeing the memory in a better and
easier way. Since these operators manipulate memory on the free
store, these are also known as free store operators.
To allocate the memory space dynamically during run time we
can use new operator & in order to free the memory space which is
allocated with new we can use the operator delete.
int *p;
- 16 float *q;
p = new int[10];
q = new float [20];
Where p is a pointer of type int and q is a pointer of type float.
When a data object is no longer needed, it is destroyed to release
the memory space for reuse, in that case we can use 'delete' operator.
Syntax:
delete pointer_variable;
delete p;
delete []p//for freeing an array of size
delete q;
sales s;
sales *q;
q =&s;
qinput() or sales.input();
qprint() or sales.print();
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
void main()
{
int n,*a,*p;
- 17 clrscr();
cout<<"ENTER NUMBER OF CELLS";
cin>>n;
a=new int[n];
for(p=a;(p-a)<n;p++)
{
cout<<"ENTER ANY VALUE TO ARRAY :";
cin>>*p;
}
clrscr();
for(p=a;(p-a)<n;p++)
{
printf("THE CELL NUMBER IS
%d\t:",(p-a));
\n:",p);
cout<<"VALUE OF ARRAY
:"<<*p<<endl;
}
delete a;
getch();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class st
{
int sno, m1, m2, m3;
- 18 char sna[20];
public:
void accept()
{
cout<<"ENTER STUDENT NUMBER:";
cin>>sno;
cout<<"ENTER STUDENT'S NAME:";
cin>>sna;
cout<<"ENTER THE MARKS OF THREE SUBJECTS:";
cin>>m1>>m2>>m3;
}
int get_tot()
{
return(m1+m2+m3);
}
void print()
{
cout<<"STUDENT NUMBER IS:"<<sno<<endl;
cout<<"STUDENT'S NAME IS:"<<sna<<endl;
cout<<"MARKS IN THREE SUBJECTS
ARE:"<<m1<<"\t"<<m2<<"\t"<<m3<<endl;
}
};
void main()
{
st *p,*p1;
int tot,av,n;
clrscr();
cout<<"ENTER NUMBER OF CELLS:";
- 19 cin>>n;
p=new st[n];
for(p1=p;(p1-p)<n;p1++)
p1->accept();
clrscr();
cout<<"THE VALUE OF THE ARRAY IS :";
for(p1=p;(p1-p)<n;p1++)
{
tot=p1->get_tot();
av=tot/3;
printf("THE ADDRESS OF CELL IS \n",p1);
cout<<"THE VALUE OF CELL IS
:"<<(p1-p)<<endl;
p1->print();
cout<<"TOTAL MARKS ARE :"<<tot<<endl;
cout<<"AVERAGE MARKS ARE :"<<av<<endl;
getch();
}
delete p;
}
Function Overloading
'Function overloading' means we have to perform the different
operations by using the same method.
The compiler will come to know the execution of a particular
function depending on the maching of number of arguments & their
return type during the function call
In the above example we are using the same method 'sum' but
the first method 'sum' performing it's operation by taking only one
argument of 'type' & the second method 'sum' performing its operation
by taking two arguments of type 'int' and so on.
Ex:sum(15) //will make a call to first function sum
sum(25,60)//will make a call to second function sum
STATIC MEMBERS
If we want to declare the data members that is common to all
the objects created in that class we have to declare those data
members as the static data members & the syntax for declaring static
data member is
static data-type variable-name; Ex: static int a;
The above data member 'a' will be shared by all the objects created in
that class i.e only one copy of that data member is created for all the
object without creating a separate copy. Whenever we create a data
member as a static it will be initialized to '0' automatically, and we can
define the value for the static data members outside the class i.e with
the help of the scope resolution operator & it's syntax is
data-type class-name :: data-member-name=value
Ex:
int example :: a; It means the value of a is initialized to 0
int example :: a=10; It means the value of a is initialized to 10
Inheritance:
- 22 The main class is called as 'base class' & the class which is acquiring
the features of the base class is called as derived class & the syntax
for defining the derived class is
'access-specifer'
specifies
the
method
of
accessing
the
information provided in the base class & it will be accessed in any one
of the three ways.
1. private
2. protected
3. public
base
private
protected
public
derived
will become
''
private
private
private
base
private
derived
will become
private
- 23 protected
"
protected
public
"
protected
base
derived
private
will become
private
protected
"
private
public
"
public
In all the above three cases the 'private' data members of the
base class is not inheritable. If we want to access those 'private' data
members we have to declare a function in 'public' mode
in the base
class & with that member function we can access them in the derived
class
If we want to define those data members in the derived class itself we
have declare those data members in 'protected' mode, but these will be
available up to one level only i.e it's accessible to the immediate class
which is accessing it's features
Both 'private' & 'protected' data members are not accessible in the
main() function. 'public' data-members & member functions will be
accessible anywhere in our program i.e they are accessible in the
main() function also
The derived class inherits some or all the properties of the base
class. A class can also inherit properties from more than one class of
from more than one level.
name
{
};
-------
-------
-------
base class
- 25 The colon (:) indicates that the derived class name is derived
from the base class name. The visibility mode is optional and if
present, it may be either private or public. The default visibility mode
is private. This mode specifies whether the features of the base class
are privately derived or publicly derived.
When a base class is privately inherited by a derived class,
public members of the base class become private members of the
derived class and therefore the public members of the base class can
only be accessed by the member functions of the derived class. They
are inaccessible to the objects of the derived class. A public member of
a class can be accessed by its own objects using the dot operator. The
result is that no member of the base class is accessible to the objects
of the derived class.
When a base class is publicly inherited by a derived class,
public members of the base class becomes the pubic members to the
derived class and therefore they are accessible to the objects of the
dedrived class.
In both the cases private members are not inherited and
therefore the private members of a base class will never become the
members of it's derived class.
E.g.:
class B:public A
{
- - - - - - //members of class B
---------------};
# include <iostream.h>
# include <conio.h>
class a
{
int x,y;
void input(int p,int r)
{
x=p;
y=r;
}
void print()
{
cout<<"X VALUE IS :"<<x<<endl;
cout<<"Y VALUE IS :"<<y<<endl;
}
class b:public a
{
int m,n;
public:
void accept()
{
cout<<"ENTER TWO INTEGERS :";
cin>>m,n;
}
void display()
{
cout<<"M VALUE IS
:"<<m<<endl;
- 27 cout<<"N VALUE IS
:"<<n<<endl;
}
};
void main()
{
b t;
clrscr();
t.input(253,445);//member function of base class
t.accept();
clrscr();
t.print();
# include <iostream.h>
# include <stdio.h>
# include <string.h>
# include <conio.h>
class student
{
int sno;
char sna[10],sadd[10];
public:
void input()
{
"<<sno<<endl;
"<<sadd<<endl;
}
};
class fees:public student
{
int tf,fp,due;
char cou[10];
public:
void accept()
{
cout<<"ENTER COURSE NAME
:";
cin>>cou;
cout<<"ENTER TOTAL FEE
:";
cin>>tf;
cout<<"HOW MUCH FEE IS PAID
cin>>fp;
due=tf-fp;
}
:";
- 29 void display()
{
cout<<"COURSE NAME IS
:"<<cou<<endl;
:"<<fp<<endl;
cout<<"DUE FEE IS
:"<<tf-fp<<endl;
}
};
class marks:public fees
{
int tm,mm,mp,mc,am;
char res[15];
public:
void marksin()
{
cout<<"ENTER MARKS IN MATHS :";
cin>>mm;
cout<<"ENTER MARKS IN PHYSICS
:";
cin>>mp;
cout<<"ENTER MARKS IN CHEMISTRY :";
cin>>mc;
}
void resout()
{
tm=mm+mp+mc;
am=tm/3;
if(am>75)
strcpy(res,"DISTINCTION");
else if(am>=60)
- 30 strcpy(res,"FIRST CLASS");
else if(am>=50)
strcpy(res,"SECOND CLASS");
else if(am>=35)
strcpy(res,"THIRD CLASS");
else
strcpy(res,"FAILED");
cout<<"MARKS IN MATHS ARE
:"<<mm<<endl;
:"<<mp<<endl;
:"<<mc<<endl;
:"<<am<<endl;
cout<<"RESULT IS--------------:"<<res<<endl;
}
};
void main()
{
clrscr();
marks obj; //object declaration
obj.input();//member function of class student
obj.accept();//member function of class fees
obj.marksin();//member function of class marks
clrscr();
obj.output(); //member function of class student
obj.display();//member function of class fees
obj.resout();//member function of class marks
getch();
}
- 31 -
Multiple Inheritance:
A class can inherit the attributes of two or more classes. This is
known as multiple inheritance. Multiple inheritance allows combining
the features of several existing classes as a starting point for defining
a new class.
Syntax:
class derived_class : visibility label base class, visibility label base
class
{
-- - - - - - - - - ------------------------------}
Where visibility label is either public or private. Comma
separate the base classes.
Protected Members:
C++ provides a third visibility modifier protected, which serve a
limited purpose in inheritance. A member declared as protected is
accessible by the member functions with in its class and any class
derived from it as the public member of the base class. It cannot be
accessed by the functions outside these classes.
When a protected member is inherited in public mode, it
becomes protected in the derived class too and therefore it is
accessible by the member functions of the derived class. It is also
ready for further inheritance.
- 32 -
E.g.:
class A
{
protected:
int a;
------------------};
class B:public A
{
- - - - - - //members of class A are
- - - - - - //protected to class B
-----};
class C:private B
{
- - - - - - //members of class A are
- - - - - - //private to class C
-----};
class D:public C
{
Example
Program
For
Multiple
Inheritance
And
Protected
# include <iostream.h>
# include <conio.h>
class employ
{
protected:
int eno,bs;
char ena[10],eadd[15];
public:
void input()
{
cout<<"ENTER EMPLOY NUMBER :";
cin>>eno;
cout<<"ENTER EMPLOY NAME
:";
cin>>ena;
cout<<"ENTER EMPLOY ADDRESS :";
cin>>eadd;
cout<<"ENTER BASIC SALARY
cin>>bs;
}
};
:";
- 34 class allow
{
protected:
int da,hra,cca;
public:
void accept()
{
cout<<"ENTER DA:";
cin>>da;
cout<<"ENTER HRA:";
cin>>hra;
cout<<"ENTER CCA:";
cin>>cca;
}
};
class ded
{
protected:
int pf,it;
public:
void dedinput()
{
cout<<"ENTER PROVIDENT FUND:";
cin>>pf;
cout<<"ENTER INCOME TAX:";
cin>>it;
}
};
class salary:public employ,public allow,public ded
- 35 {
int tall,tded,gs,ns;
public:
void calc_sal()
{
tall=da+hra+cca;
tded=pf+it;
gs=bs+tall;
ns=gs-tded;
}
void output()
{
cout<<"EMPLOY NUMBER IS:"<<eno<<endl;
cout<<"EMPLOY NAME IS
:"<<ena<<endl;
cout<<"EMPLOY ADDRESS IS
:"<<eadd<<endl;
cout<<"BASIC SALARY IS
:"<<bs<<endl;
cout<<"EMPLOY'S DA IS
cout<<"EMPLOY'S HRA IS
:"<<hra<<endl;
cout<<"EMPLOY'S CCA IS
:"<<cca<<endl;
cout<<"EMPLOY'S PF IS
:"<<pf<<endl;
cout<<"EMPLOY'S IT IS
:"<<it<<endl;
cout<<"TOTAL ALLOWANCES
:"<<tall<<endl;
cout<<"TOTAL DEDUCTIONS
:"<<tded<<endl;
:"<<gs<<endl;
:"<<ns<<endl;
}
};
void main()
{
:"<<da<<endl;
- 36 salary s;
s.input();
s.accept();
s.dedinput();
clrscr();
s.calc_sal();
s.output();
getch();
}
Hierarchical Inheritance:
In the hierarchical inheritance different classes are derived from
one base class. A subclass can be constructed by inheriting the
properties of the base class. A subclass can serve as a base class for
the lower classes and so on.
:";
- 37 cin>>sno;
cout<<"ENTER STUDENT'S NAME :";
cin>>sna;
cout<<"ENTER STUDET'S ADDRESS
:";
cin>>sadd;
}
void output()
{
cout<<"STUDENT'S NUMBER IS
:"<<sno<<endl;
cout<<"STUDENT'S NAME IS
:"<<sna<<endl;
cout<<"STUDENT'S ADDRESS IS
:"<<sadd<<endl;
}
};
class lang
{
int mt,me;
public:
void accept()
{
cout<<"ENTER MARKS IN TELUGU:";
cin>>mt;
cout<<"ENTER MARKS IN ENGLISH
:";
cin>>me;
}
void display()
{
:"<<mt<<endl;
:"<<me<<endl;
- 38 };
class mathes:public lang
{
int mm,mp,mc;
public:
void sentry()
{
cout<<"ENTER MARKS IN MATHS :";
cin>>mm;
cout<<"ENTER MARKS IN PHYSICS
:";
cin>>mp;
cout<<"ENTER MARKS IN CHEMISTRY:";
cin>>mc;
}
void sprint()
{
cout<<"MARKS IN MATHS ARE
:"<<mm<<endl;
:"<<mp<<endl;
:"<<mc<<endl;
- 39 cin>>mmt;
cout<<"ENTER MARKS IN PHYSICS
:";
cin>>mph;
cout<<"ENTER MARKS IN COMPUTERS:";
cin>>mcs;
}
void sprint()
{
cout<<"MARKS IN MATHS ARE
:"<<mmt<<endl;
:"<<mph<<endl;
:"<<mcs<<endl;
cout<<"TOTAL MARKS
ARE
:"<<mt+me+mmt+mph+mcs<<endl;
}
};
class arts:public lang
{
int mhs,mec,mci;
public:
void sentry()
{
cout<<"ENTER MARKS IN HISTORY
:";
cin>>mhs;
cout<<"ENTER MARKS IN ECONOMICS:";
cin>>mec;
cout<<"ENTER MARKS IN CIVICS :";
cin>>mci;
}
void sprint()
- 40 {
cout<<"HISTORY MARKS ARE
:"<<mhs<<endl;
- 41 a.sprint();
getch();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
# include <string.h>
class student
{
protected:
int sno;
char sna[20],sadd[25];
public:
void input()
{
cout<<"ENTER STUENT NUMBER :";
cin>>sno;
cout<<"ENTER STUDENT'S NAME :";
cin>>sna;
cout<<"ENTER STUDENT'S ADDRESS:";
cin>>sadd;
}
};
class test:public student
{
- 42 protected:
int mm,mp,mc;
public:
void mentry()
{
cout<<"ENTER MARKS IN MATHS :";
cin>>mm;
cout<<"ENTER MARKS IN PHYSICS
cin>>mp;
cout<<"ENTER MARKS IN CHEMISTRY:";
cin>>mc;
}
};
class sports
{
protected:
int sm;
public:
void sentry()
{
cout<<"ENTER SPORTS MARKS
:";
cin>>sm;
}
};
class result:public test, public sports
{
int tot,avg;
char res[20];
public:
:";
- 43 void findres()
{
tot=mm+mp+mc;
avg=tot/3;
if(sm>50)
avg=avg+5;
if(avg>=75)
strcpy(res,"DISTINCTION");
else if(avg>=60)
strcpy(res,"FIRST CLASS");
else if(avg>=50)
strcpy(res,"SECOND CLASS");
else if(avg>=35)
strcpy(res,"THIRD CLASS");
else if(avg<35)
strcpy(res,"FAILED");
}
void display()
{
cout<<"STUDENT NUMBER IS
cout<<"STUDENT'S NAME IS
:"<<sno<<endl;
:"<<sna<<endl;
:"<<mm<<endl;
:"<<tot<<endl;
:"<<avg<<endl;
:"<<res<<endl;
- 44 };
void main()
{
result r;
clrscr();
r.input(); //member function of student class
r.mentry(); //member function of test class
r.sentry(); //member function of sports class
r.findres(); //member function of result class
clrscr();
r.display();
getch();
}
Friend function
A friend function is a special function which is not a member
of any class but it is declared to access the private member data
& functions provided in that class.
C++ allows a common function to be made friendly with one or
more classes, there by allowing the function to have access to the
private data of these classes, such a function need not be a member of
any of these classes, only thing is to declare that function as a friend
to the class.
- 45 {
private:
member declaration;
public:
member function declaration;
- 46 # include <conio.h>
class sample;
class myclass
{
int a;
public:
void input()
{
cout<<"ENTER VALUE FOR A:";
cin>>a;
}
void output()
{
cout<<"A VALUE IS
:"<<a<<endl;
}
friend int getsum(myclass m,sample a)
};
class sample
{
int x;
public:
void accept()
{
cout<<"ENTER A VALUE
:";
cin>>x;
}
//friend function declaration
friend int getsum(myclass m,sample s)
};
:"<<t<<endl;
getch();
}
2nd Example for a Friend Function.
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class allow;
class ded;
class employ
{
int eno,bs;
char ena[10];
- 48 public:
void accept()
{
cout<<"ENTER EMPLOY NUMBER :";
cin>>eno;
cout<<"ENTER EMPLOY NAME
:";
cin>>ena;
cout<<"ENTER BASIC SALARY
:";
cin>>bs;
}
friend void calc_sal(employ e,allow a,ded d);
};
class allow
{
int da,hra,cca;
public:
void getallow()
{
cout<<"ENTER DA, HRA, CCA :"<<endl;
cin>>da>>hra>>cca;
}
friend void calc_sal(employ e,allow a,ded d);
};
class ded
{
int pf,it;
public:
void getded()
{
:"<<e.ena<<endl;
:"<<e.bs<<endl;
cout<<"DA IS
:"<<a.da<<endl;
cout<<"HRA IS
:"<<a.hra<<endl;
cout<<"CCA IS
:"<<a.cca<<endl;
cout<<"PF IS
:"<<d.pf<<endl;
cout<<"IT IS
:"<<d.it<<endl;
cout<<"GROSS SALARY IS
:"<<gs<<endl;
- 50 clrscr();
emp.accept();
all.getallow();
s.getded();
calc_sal(emp,all,s);
getch();
}
:"<<a<<endl;
cout<<"B VALUE IS
:"<<b<<endl;
}
friend sample setsum(sample x,test y);
};
:"<<endl;
- 51 class test
{
int m;
float n;
public:
void accept()
{
cout<<"ENTER INTEGER AND FLOAT
cin>>m>>n;
}
void print()
{
cout<<"M VALUE IS
:"<<m<<endl;
cout<<"N VALUE IS
:"<<n<<endl;
}
friend sample setsum(sample x,test y);
};
sample setsum(sample x,test y)
{
sample r;
r.a=x.a+y.m;
r.b=x.b+y.n;
return r;
}
void main()
{
sample s,p;
test t;
clrscr();
:"<<endl;
- 52 s.input();
t.accept();
clrscr();
p=setsum(s,t);
cout<<"VALUE OF FIRST OBJECT IS
:"<<endl;
s.display();
cout<<"VALUE OF SECOND OBJECT IS
:"<<endl;
t.print();
cout<<"VALUE OF RESULT OBJECT IS
:"<<endl;
p.display();
getch();
}
Constructors
A constructor is a special member function whose task is to
initialize the objects or variables of a class. The constructor is invoked
implicitly (automatically) whenever an object is created. It is called
constructor, because it will be called implicitly upon the construction
of an object.
A constructor is declared as follows.
class class_name
{
data members;
public:
class_name(arguments) //constructor
{
statements;
- 53 }
};
E.g.:
class sample
{
private:
int a,b;
float x,y;
public:
sample() //constructor function
{
a=100;
b=200;
x=35.15;
y=564.25;
}
};
void main()
{
clrscr();
sample s;
getch();
}
Characteristics of a constructor
1. It should have the same name as the class name
2. They are invoked automatically when the objects are
created.
Parameterized
any no. of
arguments.
3. Copy constructor: It will take a reference of an object as an
argument.
- 55 {
a=230;
b=654.13;
c=54865;
}
void output()
{
cout<<"INTEGER VALUE IS :"<<a<<endl;
cout<<"FLOAT VALUE IS
cout<<"LONG VALUE IS
:"<<b<<endl;
:"<<c<<endl;
}
};
void main()
{
clrscr();
test t,s,r;
clrscr();
cout<<"VALUES OF T ARE
:"<<endl;
t.output();
cout<<"VALUES OF S ARE
:"<<endl;
s.output();
cout<<"VALUES OF R ARE
:"<<endl;
r.output();
getch();
}
- 56 # include <iostream.h>
# include <conio.h>
class stud
{
int sno,tf,fp,due;
char sna[10],cou[10];
public:
stud()
{
cout<<"enter student's number
:";
cin>>sno;
cout<<"enter student's name :";
cin>>sna;
cout<<"enter course name
:";
cin>>cou;
cout<<"enter total fee is
:";
cin>>tf;
cout<<"enter fee paid
:";
cin>>fp;
due=tf-fp;
}
void output()
{
cout<<"student's number is :"<<sno<<endl;
cout<<"student's name is
:"<<sna<<endl;
cout<<"course name is
:"<<cou<<endl;
cout<<"total name is
:"<<tf<<endl;
cout<<"fee paid is
:"<<fp<<endl;
cout<<"due fee is
:"<<due<<endl;
- 57 }
};
void main()
{
clrscr();
stud s,t,u;
clrscr();
cout<<"values of s"<<endl;
s.output();
cout<<"values of t"<<endl;
t.output();
cout<<"values of u"<<endl;
u.output();
getch();
}
- 58 strcpy(sna,n);
samt=b;
}
void output()
{
cout<<"SALES MAN NUMBER IS
:"<<sno<<endl;
:"<<sna<<endl;
cout<<"SALES AMOUNT IS
:"<<samt<<endl;
}
};
void main()
{
clrscr();
sales t(100,"RAVI",2500);
sales b=sales(101,"KIRAN",3000);
cout<<"VALUES OF T
:"<<endl;
t.output();
cout<<"VALUES OF B
:"<<endl;
b.output();
getch();
}
Constructor(arglist) : initialization-section
{
assignment section
}
Destructor
A destructor as the name implies, is used to destroy the objects
that have been created by a constructor. Like a constructor, the
destructor is also a member function whose name is same as the class
name and is preceded by a tilde (~) symbol.
takes any arguments nor returns any value.
A destructor neither
It will be invoked
implicitly by the compiler upon exit from the program to clean up the
storage that is no longer accessible.
The destructor fulfills the opposite functionality. It is automatically
called when an object is destroyed, either because its scope of
existence has finished (for example, if it was defined as a local object
within a function and the function ends) or because it is an object
dynamically assigned and it is released using the operator delete.
The destructor must have the same name as the class, but preceded
with a tilde sign (~) and it must also return no value.
The use of destructors is especially suitable when an object assigns
dynamic memory during its lifetime and at the moment of being
Operator Overloading
C++ has the ability to provide the special meaning to an existing
operator. The mechanism of giving such special meaning to an
operator is known as operator overloading.
This is done with help of a special function, called operator function,
which describes the task.
Syntax:
The basic
difference is a friend function will have only one argument for unary
operator & two for binary operator. But the member function will have
no arguments for unary operator & one argument for binary operator
# include <iostream.h>
# include <conio.h>
class exam
{
int a;
float b;
long c;
public:
exam()
{
a=10;
b=25.65;
//constructor function
- 62 c=42500;
}
exam operator ++() //operator overloading function
{
a+=100;
b+=100;
c+=100;
return *this;
}
void print()
{
cout<<"A VALUE IS
:"<<a<<endl;
cout<<"B VALUE IS
:"<<b<<endl;
cout<<"C VALUE IS
:"<<c<<endl;
}
};
void main()
{
exam e;
int x=15;
clrscr();
cout<<"VALUE BEFORE FUNCTION CALLING
e.print();
cout<<"x value is :"<<x<<endl;
++e;
x++;
cout<<"value after function calling "<<endl;
e.print();
:"<<endl;
Output:
value is 15.
Values after function calling
A value is 110, B value is 125.65, C value is 142000 and
X value is 16.
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class sample
{
int a,b;
float m,n;
public:
void get_data()
{
cout<<"ENTER ANY TWO INTEGERS AND TWO FLOATS
cin>>a>>b>>m>>n;
}
void print()
{
cout<<"FIRST INTEGER IS
:"<<a<<endl;
:";
- 64 cout<<"SECOND INTEGER IS
:"<<b<<endl;
cout<<"FIRST FLOAT IS
:"<<m<<endl;
cout<<"SECOND FLOAT IS
:"<<n<<endl;
void main()
{
sample p,q,r;
clrscr();
p.get_data();
q.get_data();
clrscr();
r=p+q; //function calling
cout<<"values of first object
:"<<endl;
p.print();
cout<<"values of second object
q.print();
:"<<endl;
:"<<endl;
r.print();
getch();
}
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
class sales
{
int sno,nou;
char sna[10];
public:
sales()
//constructor
{
cout<<"ENTER SALES MAN NUMBER
:"<<endl;
cin>>sno;
cout<<"ENTER SALES MAN NAME :"<<endl;
cin>>sna;
cout<<"ENTER NUMBER OF UNITS
:"<<endl;
cin>>nou;
}
void print()
{
cout<<"SALES MAN NUMBER IS
:"<<sno<<endl;
:"<<sna<<endl;
:"<<nou<<endl;
- 66 }
int operator *(int n)
{
return(nou * n);
}
};
void main()
{
sales s;
int rpu,samt;
clrscr();
cout<<"ENTER RATE PER UNIT
:"<<endl;
cin>>rpu;
clrscr();
samt=s*rpu; //operator function calling
s.print();
cout<<"RATE PER UNIT IS
:"<<rpu<<endl;
cout<<"SALES AMOUNT IS
:"<<samt<<endl;
getch();
}
Abstract class:
An abstract class is one that is not used to create objects. It is
designed only to act as a base class upon which the other classes may
build.
Polymorphism:
This information is
known to the compiler at the compile time and therefore, the compiler
is able to select the appropriate function for a particular call at the
compile time itself. This is called early binding or static binding or
static linking. Its also known as compile time polymorphism, early
binding simply means that an object is bound to its function call at
compile time.
2. Runtime polymorphism
a. Virtual functions
Pointers to Objects:
Object pointers are useful for creating objects at run-time. We
can also use an object pointer to access the public members of an
object. The syntax for defining a pointer to an object is
- 68 -
The above statement allocates enough memory for the data members
in the object structure and assigns the address of the memory space
to ptr.
Virtual functions:
A virtual function is a member function of a class, whose
functionality can be over-ridden in its derived classes. It is one that is
declared as virtual in the base class using the virtual keyword. The
virtual nature is inherited in the subsequent derived classes and the
virtual keyword need not be re-stated there. The whole function body
can be replaced with a new set of implementation in the derived class.
- 69 more virtual functions contains a virtual pointer called the vptr at the
very beginning of the object in the memory. Hence the size of the
object in this case increases by the size of the pointer. This vptr
contains the base address of the virtual table in memory. Note that
virtual tables are class specific,
i.e., there is only one virtual table for a class irrespective of the
number of virtual functions it contains. This virtual table in turn
contains the base addresses of one or more virtual functions of the
class. At the time when a virtual function is called on an object, the
vptr of that object provides the base address of the virtual table for
that class in memory. This table is used to resolve the function call as
it contains the addresses of all the virtual functions of that class. This
is how dynamic binding is resolved during a virtual function call.
(1) Data transfer between the console unit and the program
(2) Data transfer between the program and a disk file
The I/O system of C++ contains a set of classes that define the file
handling methods. These include ifstream, ofstream and fstream.
These classes are derived from fstreambase
Class
Contents
fstreambase
ifstream
default
input mode. Inherits the functions get(),getline(),
read(),
seekg() and tellg() functions from ostream
ofstream
- 72 -
fstream
For opening a file we must first create a file stream and then
link to the file name. A file stream can be defined using the classes
ifstream, ostream, and fstream that are contained in the header file
fstream.
whether we want to read data from file or write data to it. A file can be
opened in two ways.
The first method is used when we use only one file in the
system.
Ex:ifstream fin;
Stream-object.open(filename,mode);
Meaning
ios::in
ios::out
ex:
if(fin1.eof()!=0)
{
exit(1);
}
eof() is a member function of ios class. It returns a non-zero
value if the end of the file is encountered and a zero otherwise.
Fail() This method returns true when an input or output operation has
failed
READ() AND WRITE(): To read and write the class objects onto the file
we have to use the methods read() and write() and its syntax is
ios::in
ios::out
ios::binar
y
If this flag is not set to any value, the initial position is the
beginning of the file.
All output operations are performed at the end of the file,
ios::app
ofstream
ios::out
ifstream
ios::in
fstream
ios::in | ios::out
For
ifstream
and
ofstream
classes,
ios::in
and
ios::out
are
- 76 specifying any value for the mode parameter. If the function is called
with any value in that parameter the default mode is overridden, not
combined.
Templates
Templates in one the important features of C++ which enables
us to create generic programming. It is an approach where generic
types are used as parameters in algorithms so that they work for a
variety of suitable data types and data structures. It can be
considered as a kind of macro. They are also called as parameterized
classes or functions.
- 77 -
# include <iostream.h>
# include <conio.h>
template<class A>
A add(A x,A y)
{
return x+y;
}
void main()
{
int m,n;
float f,p;
long l,r;
clrscr();
cout<<"ENTER TWO INTERGER
:"<<endl;
cin>>m>>n;
cout<<"ENTER TWO FLOATS :"<<endl;
cin>>f>>p;
cout<<"ENTER TWO LONGS
:"<<endl;
cin>>l>>r;
cout<<"FIRST INTEGER IS
:"<<m<<endl;
:"<<p<<endl;
:"<<r<<endl;
- 79 cout<<"SUM OF LONGS IS
:"<<add(l,r)<<endl;
getch();
}
Example
Program
to
Template
Functions
Templates.
# include <iostream.h>
# include <stdio.h>
# include <conio.h>
template<class A,class B>
A add (A x,B y)
{
return(x+y);
}
void main()
{
int m;
float f;
long l;
clrscr();
cout<<"ENTER AN INTEGER :"<<endl;
cin>>m;
cout<<"ENTER A FLOAT VALUE :"<<endl;
cin>>f;
cout<<"ENTER A LONG VALUE :"<<endl;
cin>>l;
clrscr();
cout<<"INTEGER VALUE IS :"<<m<<endl;
cout<<"FLOAT VALUE IS
:"<<f<<endl;
cout<<"LONG VALUE IS
:"<<l<<endl;
with
Multiple
:"<<add(l,f)<<endl;
- 81 cout<<"FIRST VALUE IS
:"<<n<<endl;
:"<<f<<endl;
}
};
void main()
{
sample <int> T1; //object declared with integer members
sample <float> T2;
clrscr();
cout<<"ENTER INTEGER VALUES :"<<endl;
T1.input();
cout<<"ENTER FLOAT VALUES :"<<endl;
T2.input();
cout<<"ENTER LONG VALUES :"<<endl;
T3.input();
clrscr();
cout<<endl<<"INTEGER VALUES ARE :"<<endl;
T1.output();
cout<<"TOTAL VALUE IS :"<<T1.total()<<endl;
cout<<endl<<"FLOAT VALUES ARE :"<<endl;
T2.output();
cout<<"TOTAL VALUE IS :"<<T2.total()<<endl;
cout<<endl<<"LONG VALUES ARE :"<<endl;
T3.output();
cout<<"TOTAL VALUE IS :"<<T3.total()<<endl;
getch();
}