Final Notes
Final Notes
Introduction of C++
Key concepts of OOPS:
UNIT-I: Objects
Introduction to C++: Key concepts of OOPs Advantages object Classes
Methods
oriented languages Input and output in C++ -Streams in C++ - Pre-
Data Abstraction
Defined Streams Unformatted console I/O operation Formatted Encapsulation
console I/O operations C++ Declarations Control structures: Inheritance
Decision Making statements If....Else Jump GOTO Break Polymorphism
Dynamic Binding
Continue Switch case statements Loops in C++ : For While Do...
Message Passing
While Loops Functions in C++ - In Line Functions Function Reusability
Overloading. Delagation
Genericity
Methods:
Objects:
Operation required for an object entity coded in a class.
Objects are the basic run time entities in an object-oriented system. They may represent a
operation defined in a class.
person, a place, a bank account, a table of data or any item that the program has to handle.
Action are defined in a method.
They may also represent user-defined data such as vectors, time and lists. Class contains private & public methods or number function.
Classes : Member function contains data members.
(e.g)
The entire set of data and code of an object can be made a user-defined data type with the
class student
help of class. In fact, objects are variables of the type class. Once a class has been defined,
{
we can create any number of objects belonging to that class. Each object is associated with
Private:
the data of type class with which they are created. A class is thus a collection of objects Data members;
similar types. Public:
For examples, Mango, Apple and orange members of class fruit. Classes are user-defined Method()
that types and behave like the built-in types of a programming language.
};
void main()
{
student s Polymorphism:
s.method name();
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
}
Data Abstraction: ability to take more than on form. An operation may exhibit different behavior is different
Abstraction refers to the act of representing essential features without including the background instances. The behavior depends upon the types of data used in the operation.
details or explanation.
Dynamic Binding:
(e.g) size,cost,height,weight.
Encapsulation : Binding refers to the linking of a procedure call to the code to be executed in response to
The wrapping up of data and function into a single unit (called class) is known as encapsulation. the call. Dynamic binding means that the code associated with a given procedure call is not
Data and encapsulation is the most striking feature of a class. The data is not accessible to the outside known until the time of the call at run time. It is associated with polymorphism and
world, and only those functions which are wrapped in the class can access it.
inheritance. A function call associated with a polymorphic reference depends on the
Inheritance :
dynamic type of that reference.
Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification. Message Passing:
We have used user defined data types such as structure and union in C. While these Decision making statements:
more features have been added to make them suitable for object oriented The if statement:
programming. C++ also permits us to define another user defined data type known as The if statement is implemented in two forms:
class which can be used just like any other basic data type to declare a variable. The 1. simple if statement
class variables are known as objects, which are the central focus of OOPs. 2
ENUMERATED DATA TYPE: Simple if statement:
An enumerated data type is another user defined type which provides a way for
if (condition)
attaching names to number, these by increasing comprehensibility of the code. The {
enum keyword automatically enumerates a list of words by assigning them values action;
0,1,2 and soon. This facility provides an alternative means for creating symbolic. }
Continue :
int ;
for(i-0; i<100; i++) The continue statement provides a convenient way to force an
{ immediate jump to the loop control statement. The break
If i==10) break; // terminate loop if i is 10 statement terminates the execution of the loop.
printf("i: %d \n", i);
As you can see in the given example, we have used both the
{
statements within the do while loop. The program prompts the
printf "Loop complete.");
} user to entire any number. after number is less than 0, the break
statement terminates the execution of the loop. If the number is
greater than 10, the continue statement
skips the value and jumps to the do while loop without
terminating the loop. Otherwise, it will print the entered number.
continue :
1.Skips the remaining statements in the body of a while, for or
do/while structure .Proceeds with the next iteration of the loop
2.while and do/while Loop-continuation test is evaluated
immediately after the continue statement is executed .
3. for structure Increment expression is executed, then the loop-
continuation test is evaluated .
goto Statement:
It is a welknown as jumping statement.It is primarily used to
transfer the control of execution to any place in a program. It is
useful to provide branching within a loop.
When the loops are deeply nested at that if an error occurs #include <studio.h>
then it is difficult to get exited from such loops. Simple #include <conio.h>
break statement cannot work well properly. ln this void main()
situations. goto statements used. A goto statement in C {
programming language provides an unconditional jump int a;
from the goto lo a labeled statement in the same function. start :
Syntax: printf any
goto Label; scanf &a);
if(a<0);
goto start; //Goto statement A
a=a*a;
Label: statement; printf \n %d", a);
getch();
}
Loops in C++ Example:
For
#include <iostream>
While
using namespace std;
Do while
int main()
For loop:
Syntax: {
for (initialization; condition; update) for (int i = 1; i <= 5; ++i)
{ {
//body of-loop cout << i << " ";
} }
initialization - initializes variables and is executed only once
return 0;
condition - if true, the body of for loop is executed if false, the for
loop is terminated }
update - updates the value of initialized variables and again checks the
condition
main()
int main()
{ {
int main( ) That is the compiler replaces the function call with the
{ corresponding function code.
-------------- The inline functions are defined as follows:-
-------------- inline function-header
return(0) {
} function body;
Since the return type of functions is int by default, the key word
int in the main( ) header is optional. }
INLINE FUNCTION:
Example: inline double cube (double a)
To eliminate the cost of calls to small functions C++ proposes a {
new feature called inline function. An inline function is a function return(a*a*a);
that is expanded inline when it is invoked . }
The above inline function can be invoked by statements like
c=cube(3.0); d=cube(2.5+1.5);
remember that the inline keyword merely sends a request, not a command to the //Declaration
compiler.
int add(int a, int b); //prototype 1
The compiler may ignore this request if the function definition is too long or too
int add (int a, int b, int c); prototype 2
complicated and compile the function as a normal function.
double add(double x, double y); //prototype 3
FUNCTION OVERLOADING:
double add(double p , double q); //prototype4
Overloading refers to the use of the same thing for different purposes . C++ also
permits overloading functions .This means that we can use the same function name //function call
to creates functions that perform a variety of different tasks. This is known as cout<<add(5,10); //uses prototype 1
function polymorphism in oops. Using the concepts of function overloading , a cout<<add(5,10,15); //uses prototype 2
family of functions with one function name but with different argument lists in the
cout<<add(12.5,7.5); //uses prototype 3
functions call .The correct function to be invoked is determined by checking the
cout<<add(15,10.0); //uses prototype 4
number and type of the arguments but not on the function type.
For example an overloaded add() function handles different types of data as shown
below.
Object oriented programming with C++
Class and object
The object can not be access the private variables and function Example:
directly. #include<iostream.h>
It can be accessed only by the public member function. #include<conio.h>
Syntax: Class add
class class-name {
{ Private;
Private: int x,y,z;
Declaration of variables; Public:
Declaration of functions; Void sum()
Public: {
declaration of variables; Cin>>x>>y;
declaration of functions; z=x+y;
}; }
void display() Declaring object:
{ The declaration of object is same as declaration of variables.
cout<<z;
Object are created when the memory is allocated.
}
Accessing class members:
};
void main() The object can be accessed the public member variable and function
{ using the operator.
add a1; Syntax:
a1.sum(); Object name[operator] member name;
a1.display(); Example:
a1.add();
getch();
a1.add();
}
#include<iostream.h>
cin>>sno;
#include<conio.h>
cout
Class student
cin>>sname;
{
cout
Private:
cin>>m1>>m2>>m3;
int sno,m1,m2,m3,Total;
}
char sname[20];
void total_mark()
Public:
{
void getstudent()
total=m1+m2+m3;
{
}
Cout
void print _details()
{ Private member function:
cout
cout<<sno;
It is also possible to declare private function inside the class.
cout The private member function can be accessed only by the
cout<<sname; public member function.
cout
cout<<m1<<m2<<m3; It can be accessed like a normal function.
cout<<total; Example:
}
} #include<iostream.h>
void main() #include<conio.h>
{
student s1; {
s1.getstudent();
s1.total _mark();
Private:
s1.print _details(); int sno,m1,m2,m3,total;
getch();
} Char sname[20];
void student::print_details()
{ Characteristic of Member Function
cout student
cout<<sno;
cout student
cout<<sname; The Difference between member and normal function is that
cout T normal function can be invoked freely where as the member
cout<<m1<<m2<<m3;
cout function can be accessed only by the object of the class.
cout<<total;
} The same function can be used in any number of classes.
};
void main() The private data (or) private function can be accessed by
{
Student s;
public Member Function.
s.get_student();
The member function can be accessed one another without
s.total_marks();
s.print_details(); using any object (or) . (dot) Operator.
Getch();
}
Outside member function inline
Example:
The inline mechanism reduces the overhead relating to access the #include<iostream.h>
#include<conio.h>
member function .
Class add
It provides better efficiency quick execution of function. {
Private:
Inline Function similar to Macros .call to inline function in the program int a,b,c;
places the function code in the caller program. Public:
Void get _in();
This is known as inline expansion.
Void sum();
Rules for inline function Void Print();
};
Use inline function rarely.
Void inline add:: get_in()
Inline function can be used when the member function contains few {
cin>>a>>b;
statement.
}
If a function takes more time to executed than it must to declared as
inline.
Example:
Static member Variables & Functions Static int a;
Static void display();
Static member Variables:
int sumnum::a=0;
If a member variable is declared as static only one
-Sumnum is a classs name
copy of the member is created for the whole class.
The Static member variable is to be defined outside the class declaration.
The static is a keyword used preserve the value of the
variable. The reason for defining outside the class
Syntax: 1. The static data member or associated with the class not with the object.
Static<Variable definition> 2. The Static data members are stored individually rather than an element
Static<function definition> of an object.
3. The static data member has to initialize.
4. The memory for static data is allocated only once.
int number::C=0;
5. Only one copy of static member variable is created for the whole
int main()
class.
{
Example:
number a,b,d;
#include<iostream.h>
#include<conio.h> a.count();
Class number b.count();
{ d.count();
Static int c;
Public: }
Void count() Static member function:
{
Like member variables functions can also be declared as Static.
++c;
cout<<c; When a function is static it can access only static member variables
} and functions of the same class.
};
{
count(); Static public member variable
cout \
}
The static public member variable can be initialized outside the class
}; and also can be initialized in the main function.
void bita ::c=0; It can be initialized like a normal variable.
void main() Example:
{ #include<iostream.h>
clrscr(); #include<conio.h>
bita::display(); int c=11;
bita::display(); Class bita
}
{
Output: value of C:1
Public:
Static int c;
value of C:2
};
Static Object
int bita::c=22;
void main() The object is a composition one or more variables. The
{ keyword static can be used to initialize all class data members
to zero.
clrscr();
Declaring object as static will initialize all the data members to
int c=33; zero.
cout \ bita::c; Example:
cout \ #include<iostream.h>
cout \ #include<conio.h>
Class number
}
{
Output:c=22
int c,k;
c=11
Public:
c=33
Array of Object
void plus() Array is a collection of similar data types it can be of any data type including user
{
defined data type created by struct,class,type,def declarations.
c=c+2;
k=k+2; We can also create an array of objects.
} The array elements of stored in continuous memory location.
void show()
The arrays can be initialized or accessed like an ordinary array.
{
cout<<c; Example:
cout<<k; #include<iostream.h>
} #include<conio.h>
Class student
void main()
{
{
int Sno;
static number x;
char sname[20];
x.plus(); Public:
x.show(); void get_input();
} void display();
Output : c-=2 }
k=2
Void main()
void student::get_input()
{
student s[10];
{
int n, i;
cout
cout no.of.students
cin>>sno;
cin>>n;
cout for(i=1;i<=n;i++)
cin>>sname; {
} s[i].get_input();
void student::display() }
{ For(i=1;i<=n;i++)
cout<<sno; {
cout<<sname; s[i].display();
} }
}
2. Pass by reference
Objects as Function arguments
Address of the object is implicitly sent to function.
Like variables objects can also pass to functions. 3. Pass by address
There are three methods to pass an arguments:
Address of the object is explicitly sent to function.
1. Pass by value
In this type a copy of an object is sent to function and In pass by reference and pass by address methods the address of the
assigned to object of calling function . actual object is passed to the function.
Both actual and formal copies are objects are stored in
different memory location so changes made in formal So, duplicating of the object is prevented.
objects does not reflect to actual object.
Cout \
Example: Cin>>expyr;
#include<iostream.h> }
#include<conio.h> Void period(life);
};
Class life Void life::period(life yr)
{ {
int mfgyr; yr=y1.expyr-y1.mfgyr;
cout
int expyr; }
int yr; void main()
Public: {
clrscr();
Void getyrs() life a1;
{ a1.getyrs();
cout a1.period(a1);
}
cin>>mfgyr;
Friend Function
1. There is no scope restriction for the friend function . So they
can be called directly without using objects.
Any non-member function has no access permission to the 2. Friend function cannot access the member directly . It uses
private data of the class. object and dot operator to access the private and public
The private member of the class are accessed only from the member.
member function of that class. 3. By default friendship is not shared that is if class x , if
C++ allows a mechanism in which a non-member function has declared as friend of class y. It does not mean y has rights to
access permission to the private members of the class. access private member of class x.
This can be done by declaring a non member function friend to 4. Use of friend function is rarely done because it violets rule of
the class whose private data is to be accessed. encapsulation and data hiding.
Here friend is a keyword 5. The function can be declared as public (or) private without
The friend function have the following properties: changing its meaning.
Example:
class first
#include<iostream.h>
{
#include<conio.h>
int f;
class first;
public:
class second
void get value()
{
{
int s;
public:
cin>>f;
void get value() }
{ friend void sum(second ,first);
cin>>s; };
} void sum(second d, first t)
friend void sum(second,first); {
}; cout<<t.f+d.s;
}
Friend Classes
void main()
{
It is possible to declared one or more functions as friend
first a;
second b; function or entire class can be declared as friend class.
a.get value();
The friend is not transferable or inheritable one class to
b.get value();
sum(b,a); another .
}
The friend classes are applicable when we want to make
available private data of a class to another class.
Example: Class B
#include<iostream.h> {
#include<conio.h> int b;
class B Public:
void get B()
class A
{
{
b=40;
int a; }
public: friend void A:: show(B bb);
void get A() };
{ void A:: show(B bb)
a=30; {
} cout<<a;
void show(B); cout<<bb.b;
}; }
Void main()
Overloading member function
{
Member functions are also overloaded in the same way as
A.a1; ordinary functions.
Overloading is nothing but one functions is defined with
B.b1; multiple definition with same function name.
a1.getA(); Example:
#include<iotstream.h>
b1.getB();
#include<conio.h>
a1.show(b1); #include<stdlib.h>
#include<math.h>
}
Class absv
{
Public: int main()
int num(int);
double num(double);
{
}; clrscr();
int absv::num(int x)
absvn;
{
int ans; cout \n Absolute value of - -25);
ans=abs(x); cout \n Absolute value of - -25.1474);
return(ans);
} return 0;
double absv:: num(double d) }
{
double ans;
ans=fabs(d);
return(ans);
}
Constructor & destructor The constructor may contain arguments to pass the values to
the function.
When a variable is declared and if it is not initialized it A program may contain one or more constructor.
contains garbage value. Constructors are also called when local or temporary objects of
The compiler itself cannot initialize the variable the program a class are created.
explicitly assign a value to the variable. Characteristics of Constructor
CONSTRUCTORS 1. Constructor has the same name as the class name.
The constructor constructs the object. Constructors are special 2. Constructor is executed when an object is declared.
member functions 3. Constructor have neither return value nor void.
When an object is created constructor is executed. 4. The main function of constructor is to initialize objects.
The constructor are automatically executed when the objects 5. Constructors are executed implicitly and they can be invoked
are created. explicitly.
6. Constructor can have default and can be overloaded. 4. The destructor is automatically executed when an object goes out of
7. The constructor without arguments is called default construtor. scope.
5. It is also invoked when delete operator is used to free the memory
DESTRUCTOR
allocation.
1. Destructor are special member function used to destroy the 6. Destructors are not overloaded.
object. 7. The class can have only one destructor.
2. The destructor is executed at the end of the function or at the Characteristic of destructor
end of the program. 1. Destructor has the same name as that of the class it belongs to and
proceeded by ~(tilde)
3. The destructor can be defined same as class name preceded
2. Like constructor, the destructor does not have return type and not
with ~(tilde) operators. even void.
3.Constructor and destructor cannot be inherited, though a 8. TURBO C++ compiler can define constructor and destructor if
derived class can call the constructor and destructors of the they have not been explicitly defined. They are also called on
base class. many cases without explicit calls in program. Any constructor
4. Destructor can be virtual, but constructors cannot. (or) destructor created by the compiler will be public.
5.Only one destructor can be defined in the class. The destructors 9.Constructor and destructors can make implicit calls to operators
not have any argument. new and delete if memory allocation/de-allocation is needed
for an object.
6. The destructor neither have default values nor can be
overloaded. 10. An object with a constructor or destructor cannot be used as a
member of a union.
7. Programmer cannot access addresses of constructors and
destructors.
void calculate()
{
Example: s=a+b;
#include<iostream.h> }
void display()
#include<conio.h>
{
class sum cout<<a<<b;
{ cout<<s;
int a,b,s; }
public: ~sum()
sum() {
{ cout
s=0; }
} };
void getdata() void main()
{
{
sum.s1;
cin>>a>>b; s1.getdata();
} s1.calculate();
s1.display();
}
{
a=k; Destructors
}
num(int x)
{ It will destroy the object. Destructors is also a special member
a=x.a;
}
function like constructor.
void show()
{
It destroy the class object created by constructor.
cout<<a;
The destructors have the same name as the class name
}
}; proceeded by ~(tilde)operator.
void main()
{ For local and non-static object the destructor is executed when
num n(10);
num(n); the object goes out of scope. It is not possible to define more
n.show(); than one destructor.
c.show();
} Destructor releases memory location occur the memory object.
Example:
#include<iostudio.h> Constructor and destructor with
#include<conio.h> static members
class num
{
int a; Every object has its own set of data members.
public:
num() When a member function is called only copy of data is
{
cout available to the function.
}
~num() Sometimes it is necessary for all the object to share the data
{
cout field which is common for an object.
}
}; If the member variable is declared has static.
void main()
{ Only one copy of the member is created for entire class.
num n1;
}
The static member variable used to count number of object for cout<<no;
a particular class. }
Example: ~man()
{
#include<iostudio.h>
--no;
#include<conio.h> }
class man };
{ int man::no=0;
static int no; void main()
{
char name;
man A,B,C;
int age; cout
public: }
man()
{
no++;
OBJECT ORIENTED PROGRAMMING WITH C++ 3.1 Operator Overloading
SUB CODE :18BIT23C
UNIT III: Operator Overloading: Overloading Unary Binary Overloading is an important feature of c++
Operators Overloading Friend Functions Type Conversion It is similar to function overloading. An operator is a symbol
Inheritance: Types of Inheritance Single Multilevel Multiple used for an operation.
Hierarchical Hybrid and Multi Path Inheritance Virtual Base C++ has the ability to treat the user-defined data type.
Classes Abstract Classes.
As a built in data type.
TEXT BOOK The Operator + can be used to perform addition of two
1. Ashok N Kamthane variables but it is not possible to perform addition of two
Education Publications, 2006. objects.
Operator overloading is one of the most valuable concept to
perform this type of operation.
Prepared By: Dr. M. Soranamageswari It is a type of polymorphism permit to write multiple
definitions for functions and operators.
Example
The Operator +,-,* and = are used to carry the operations of Number operator +(number D)
overloading. {
The Capability to relate the existing operator with a member Number T;
function and use the resulting operator with object of its class, T.X=X+D.X;
as its operands is called Operator Overloading.
T.Y=Y+D.Y;
Syntax:
Return T;
Return type
}
{
S+1
S+2
}
Overloaded Operators are redefined using the keyword The prototype for operator overloading can be
Operator followed by an Operator symbol. return as follows:
An Operator function should be either a member function or Void Operator ++();
Friend function. Void Operator - -();
A Friend Function requires one argument for unary operators Void Operator ();
and two for binary Operators.
Num operator + (num);
A Member function requires one argument for binary operator
and no arguments for unary Operators. Friend num operator * (int, num);
Void Operator =(num);
Example:
Syntax: Example:
Operator(num 02); 03=01 operator + (02)
Where, The callingunction can be written as,
03=01+02
Operator is a symbol
Here the data membr are passed to the called function and
Num is an class performs the number of addition based on number of
02 is the argument of the class arguments
Example: void num: :input( )
{
#include<iostream.h> cin >>a>>b>>c>>d;
#include<conio.h> }
class num void num : :show( )
{
{ cout <<a<<b<<c<<d;
int a,b,c,d; }
num : : operator+(num t)
public: {
void(input(void); m tmp;
tmp.a=a+t.a;
void show(void); tmp.b=b+t.b;
num operator + (num); tmp.c=c+t.c;
tmp.d=d+t.d;
};
return(tmp);
}
}
Example:
friend num operator + (num n1 num n2) num operator*(inta, numt)
#include <iostream.h> {
#include<conio.h> num tmp;
class num tmp.a = a*t.a;
{ tmp.b = b*t.b;
int a,b,c,d ; tmp.c = c*t.c;
public: tmp.d = d*t.d;
void input (void); return(tmp);
void show (void); }
friend num operator*(int,num); void main( )
}; {
void num : : input( ) num x,z;
{ x.input( );
cin >>a>>b>>c>>d; z=3*x;
} x.show( );
void num : : show ( ) z.show( );
{ }
cout<<a<<b<<c<<d;
}
The constants and variable of various data types are S.no Conversion type Routine in Routine in source
companied in a single expression can be automatically destination class class
converted by the compiler. 1 class to class Constructor Conversion
function,
The compiler has no knowledge about the user-defined data
(operator
type and about their conversion of other data type. function)
There are three possibilities of data conversion. 2 class to Basic - Conversion
1. Conversion from Basic data type to user-defined data function,
(operator
type(class type)
function)
2. Conversion from class type to basic data type 3 Basic to Class Constructor -
3. Conversion from one class type to another class type
Conversion type.
3.5.1 Conversion from Basic class type
Basic source and destination objects are user defined data type
the conversion routine can be carried out using operator In this type the left hand operand of (=) equal sign if always
function is source class or using constructor in destination the class type. The right hand operand is always basic type.
class. The Conversion can be done by the compiler with the helpof
If the user defined object is destination class. The conversion build routine or by applying type casting.
routine should be carried out using constructor in the It uses constructors for changing the Basic type to class type.
destination class.
If the user defined object is a source object. The conversion
routine should be carried out using source object in the
operator function.
Example:
#include<iostream.h>
#include<conio.h>
class data void show( )
{ {
int x ;
float f; cout<<x<<f;
public: }
data( ) };
{
x=0; f=0; int main ( )
} {
data(float m) data= z
{
x=2; z=1;
f=m; z.show( );
} z= 2.5
z.show( );
}
3.5.2 Conversion from class type Basic data
type
The conversion function should not have any argument
The compiler does not have any knowledge about the Do not mention return type.
user defined data type using class. It should be a class member function.
In this type of conversion the programmer explicitly specify Example:
about the conversion. #include<iostream.h>
There instruction are return in a member function. This type of #include<conio.h>
conversion also known as over loading of type cast operators. class data
In this type the left hand operand is Basic data type the right {
hand operand is class type.
int x;
To perform this conversion it must satisfy the following
condition. float f ;
void show( )
public; {
data( ) cout<<x<<f;
{ }
X=0; y=0; };
int main( )
}
{
operator int ( )
int j;
{ float f;
return(x) ; data a;
} a=5.5;
data (float (m) j=a;
{ f=a;
x=2; cout<<j;
f=m; cout<<f;
}
}
3.5.3 Conversion from one class type _
another class type
public:
There are two ways to convert one class type to another class stock1 (int a, int b, int c)
type {
One is to define a conversion operator function in source class code =a;
or a constructor in a destination class. item =b;
Example: price =c;
#include<iostream.h> }
#include<conio.h> void disp( )
class stock2: {
{ cout<<code;
int code, item; cout<<item;
float price; cout<<price;
}
1. When public access specified is used public members of the A class can be derived publicly or privately.when a class is
derived class. similarly the protected members of the base derived publicly all the public members of the base class can
class or protected member of the derived class. be accessed directly in the derived class.
The public derivation does not allow the derived class to
access private member variables of the base class.
2. When a private access specified is used public and protected
members of the base class or private members of the derived
Example:
class.
Write a program to derive a class publicly from base
class.declare the base class with its member under public
section.
#include<iostream.h>
#include<conio.h>
void main() The member functions of derived class cannot access the
{ private member variables of base class.
clrscr(); The private members of base class can be accessed using
B b; public member functions of the same class.
b.show(); To overcome this problem the protected access specifier is
used.
}
The protected is same as private but it allows the derived class
to access the private members directly.
Example:
void shows( )
#include<iostream.h>
#include<conio.h> {
class A cout \
{
cout \
protected:
int x; }
}; };
class B:private A
void main( )
{
int y; {
public: clrscr( )
B( )
B.b;
{
x=30; b.show( );
y=40; }
}
The process of inheritance can depends on the following 1.Single inheritance or simple
points. 2.Multiple inheritance
1.Number of base classes: 3.Hierarchical inheritance
The program may contain one or more base classes. 4.Multilevel inheritance
2.Number of derived classes: 5.Hybird inheritance
A program may contain one or more derived classes. 6.Multipath inheritance
Example:
3.8 single inheritance: #include<iostream.h>
#include<conio.h>
When only one base class is used for derivation of a class and Class ABC
the derived class is not used for base class. {
protected:
Inheritance between one base class and one a derived class is char name[20];
known as single inheritance. int age;
The new class is termed as derived class and the old class is };
class abc:public ABC
called base class. {
A Derived class inherit data members and member functions float height,weight;
of base class. public:
void getdata()
The Constructor and destructor of base class are not inherited. {
cin>>name>>age;
cin>>height>>weight;
}
3.10.Hierarchical inheritance
void display() A single base class is used for derivation of two or more
{ derived classes is known as hierarchical inheritance.
cout<<x<<y<<z<<d; Inheritance also support hierarchical arrangement of programs.
} Hierarchical unit source the top down arrangement of classes.
};
void main()
D.d1;
d1.getdata();
d1.display();
}
class C
Example:
#include<iostream.h> {
#include<conio.h> protected:
int z;
class A
}
{
protected: class D: public A,public B
int x; {
int d;
}
public :
class B
void getdata()
{
protected: {
int y; cin>>x>>y;
}
}
void get()
{
cout<<e<<z;
void display() }
{ };
cin<<x<<y; void main()
} {
}; E e1;
class E:public D,public C e1.getdata();
e1.display();
{ e1.get();
int e; e1.put();
public: }
3.11 Multilevel inheritance
void put()
When a class is from another derived class that it the derived
{
class act is a base class.
cout<<age<<name;
This type of inheritance is known as multilevel inheritance.
cout<<height<<weight;
Example:
cout<<sex;
#include<iostream.h>
}
#include<conio.h>
};
class A1
void main()
{
{
protected :
A3.x;
int age;
x.get();
char name[20];
x.put();
};
}
class A2:public A1
{ 3.12 Hybrid Inheritance
protected:
float height;
The combination one or more type of inheritance is known as
float weight;
hybrid inheritance.
};
class A3:publc A2 Here two types of inheritance is used. That is single and
{ multiple inheritance.
protected: x-base class
char sex; y-derived class and base class of z.
public: w-base class
void get()
{
cin>>age>>name;
cin>>height>t>weight;
cin>>sex;
}
class A4:public A2,A3
Example: {
#include<iostream.h> protected:
#include<conio.h> char address[20];
Public:
class A1
void get( )
{
{
protected: cin>>age>>name;
int age; cin>>height>>weight;
char name[20]; cin>>sex;
}; cin>>address;
class A2:public A1 }
void put( )
{
{
protected:
cout<<age<<name;
float heirght; cout<<height<<weight;
float weight; cout<<sex;
}; cout<<address;
class A3 }
{ };
void main( )
protected:
{
char sex;
A4 x;
}; x.get( );
x.put( );
}
{
protected:
3.14 Virtual base class int age;
char name[20];
};
To overcome the ambiguity occurd in multipath inheritance class A2:public virtual A1
c++ provides the keyword virtual. {
The keyword virtual declares the specified classes as virtual. protected:
float height;
It can avoid the duplication of member variables defined in the float weight;
base classes. };
Example: class A3:public virtual A1
{
#include<iostream.h> protected:
#include<conio.h> char sex;
};
class A1 class A4:public A2,A3
{
protected:
char address[20];
Public:
void get( )
{
cin>>age>>name; void main( )
cin>>height>>weight;
{
cin>>sex;
A4.x;
cin>>address;
} x.get( );
void put( ) x.put( );
{ }
cout<<age<<name;
cout<<height<<weight;
cout<<sex;
cout<<address;
}};
protected:
3.15 Abstract classes int age;
When a class is not used for creating object is called abstract char name[20];
classes. };
class abc:public ABC
The abstract classes can act as a base class. It is the layout
{
abstraction in a program and it allows the base class on several
float height,weight:
levels of inheritance.
public:
An abstract classes developed only to act as a base class for void get data( )
inheriting the properties and no object of these classes are {
declared. cin>>age>>name;
Simple inheritance cin>>height>>weight;
Example: }
#include <iostream.h> void display( )
{
#include<conio.h>
cout<<age<<name;
class ABC cout<<height<<weight;
{ } };
void main( )
{
abc x;
x.get data( );
x.display( );
}
OBJECT ORIENTED PROGRAMMING WITH C++ Pointer and arrays:
SUB CODE :18BIT23C
UNIT IV: Pointers: Declaration Pointer to Class Object THIS Pointer C++ variables are used to hold data during program execution.
Pointer to Derived Classes and Base Classes Arrays: Characteristics Arrays Every variable can occupy some memory location to hold the
of Classes Memory Models New and Delete Operators Dynamic Object data.
Binding Polymorphisms and Virtual Functions.
Memory is arranged in a sequence of byte.
TEXT BOOK The number specification to each byte is called memory
1. Ashok N Kamthane address.
Education Publications, 2006
The sequence starts from 0 onwords.
It is possible to access and display the address of memory
Prepared By: Dr. M.Soranamageswari
location using the pointer variable.
Feature of pointer:
Pointer:
Pointer is a memory variable that store a memory address. Pointer save memory space.
Pointer can have any name that is legal to other variable. Execution time with pointer is faster.
It can be declared like normal variable it is always denoted by The memory is accessed efficiently with the pointer.
star(*)operator. Pointer are used with data structure and they are useful for
representing two dimensional array.
A pointer declared to a base class can access the object of
derived class.
Pointer Declaration:
Pointer can be declared as follows: It inform to the compiler that hold the address of any variable.
Syntax: The in-direction(*)operator is also called de-reference
Data type * pointer variable name. operator.
Where as a pointer indirectly access to their own values.
Example: The (&) is the address operator represented the address of a
int *a; variable.
int *b; The address of any variable is a whole number.
float*c;
Example: Voidputdata()
{
#include<iostream.h> cout<<name<<age;
#include<conio.h> }
Classman };
{
public: void main()
char name[20]; {
int age; Man *ptr,m;
voidgetdata(char s[10],int a) ptr=&m;
{ ptr->getdata );
name =s; ptr->putdata();
age=a; }
}
Pointer to object: Example
#include<iostream.h>
#include<conio.h>
Like variable object can also have an address.
class bill
The pointer can point to a specified object. {
Using the pointer it is possible to access different type of intqty;
classes. float price;
float amount;
Syntax: public:
{
Class name*ptr variable name;
Voidgetdata(inta,floatb,float c)
{
Eg: qty=a;
Student*str; price=b;
amount=c;
}
void show()
{ This pointer:
cout \
cout \
cout \ The objects are used to invoke non static member function of
} the class.
}; The pointer this is transferred as an unseen parameters to call
int main() non static member function.
{ The keyword is a local variable always present in the
clrscr(); body of non-static member function.
bill s;
The keyword this does not need to be declared.
bill*ptr;
ptr=&s; The pointer is rarely referred explicitly in a member function.
ptr->getdata(45,10.25,45*10.25); It is used implicitly with in the function for member reference.
(*ptr).show(); Using this pointer it is possible to access the individual
return 0; member variables of the object.
}
void show()
Example: {
Program to use this pointer and return pointer cout<<num;
reference(minimum or smallest value of two numbers) }
#include<iostream.h> number min(number t)
#include<conio.h> {
Class number if(t.num<num)
{ return t;
Public: else
intnum; return *this;
void input() }
{ };
cin>>num;
}
Example Example
int a[5]={1,2,3,4,5};
The range of elements begins from zero(0) memory location. #include<iostream.h>
Characteristics of arrays :- #include<conio.h>
All the elements of an array of the same name and they are differentiated
class arraytest
from one another with the help of elements number.
The element number in an array is the most important factor in calling each {
element. int a[10];
Any particular element of an array can be modified without disturbing the public:
other element.
Any element of an array can be assigned to another ordinary variable (or) void get();
array variable of its type. void display();
The array elements are stored in continuous memory locations, the amount };
of storage required for the elements depends on its type and size
Total bytes=sizeof( data type)*sizeof(array)
void arraytest::get()
{
for(int i=1;i<=10;i++)
{ void main()
cin>>a[i];
{
}
arraytest a1;
}
a1.get();
void arraytest::display()
{
a1.display();
for(int i=1;i<=10;i++) }
{
cout<<a[i];
}
}
Example
Array of classes :- #include<iostream.h>
#include<conio.h>
An array is a collection of similar data type in the same way it Class student
is also possible to define array of classes.
{
Here array is a class type array of class object can be declared
Char sname[20];
as follows:
Char grade;
class student
int sno;
{
Public:
char sname[20];
void get();
student s[10];
void display()
int sno[10];
};
char sadr[20];
}
void student::get()
{
void main()
cin>>sname;
{
cin>>sno; student S[10];
cin>>grade; int n,i;
} cout
cin>>n;
void student::display()
{ for(i=1;i<=n;i++)
cout<<sname; {
cout<<sno; S[i].get();
}
cout<<grade;
for(i=1;i<=n;i++)
} {
S[i] display();
}
}
Delete operator :-
The delete operator frees the memory location allocated the Size of operator
operators. The sizeof operator is used to returns the size of your variable
bytes.
Syntax
Delete pointer variable name; Syntax
Delete [element size] pointer variable name; sizeof (variable name);
Example
Delete a; Example
Delete[50] a; Cout<<sizeof(a);
Few points regarding : new and delete
operators are :-
The new operator not only creates an object but also allocates The statement delete x does not destroy the pointer x.
memory. It destroy the object.
The new operator allocates correct amount of memory from If the object created is not deleted it occupy the unnecessarily.
the heap that also called a free store. It is a good habit to destroy the object and release the system
The object created and memory allocated using new operator resources.
should be deleted by the delete operator.
The delete operator not only destroys the object but also
returns the allocated memory.
The new operator creates an object and its remains in the
memory until it is released using delete operator.
If we sent a null pointers to delete operator it is secure using
delete to zero(0) has no result.
Example
#include<iostream.h>
#include<conio.h>
The new operator returns the address of the object created and
class data
it is stored in the pointer(ptr).
{
Ptr is a pointer variable is the same class.
int x,y;
The member variables of object can be accessed using operator
public:
The dynamic object can be destroy using delete operator.
data()
{
Syntax:
cout \
delete ptr;
x=10;
It destroy the object pointed by pointer ptr.
y=50;
}
~data(){cout \
void display()
{
cout \ Binding ,polymorphism and virtual functions
cout \ Binding:-
} In c++ functions can be bound either at complied time (or) at
}; run time designing the function call at compile time is called
void main() compile time (or)early(or)static binding.
{ Designing function call at run time is called as run
clrscr(); time(or)late(or)dynamic binding .
data*d; Dynamic binding permits the decision of choosing suitable
d=new data; function until run time.
();
delete d;
}
Similar function name are used at many places but during their int k;
references their position is indicates explicitly . public:
Their ambiguities are fixed at compile time. void display()
Example: {
class first cout<<k;
{ }
int d; }
public:
void display()
{cout<<d;}
};
2. Dynamic (or) late binding :
Example:
#include<iostream.h>
Dynamic binding of member function in c++ can be done
#include<conio.h>
using the keyword VIRTUAL
class data
The member function followed by virtual keyword is called as
virtual function. {
The virtual function must be defined in public section. int x,y;
If the function is declared virtual,the system will use dynamic public:
binding data()
Which is carried out at runtime {
cout \
x=10;
y=50;
}
Function
Virtual function Operator overloading
overloading
Virtual destructors
void main()
{
B*P;
P=new D;
delete P;
}
OBJECT ORIENTED PROGRAMMING
WITH C++ Applications With Files:
SUB CODE :18BIT23C
UNIT V: Files: File Stream Classes File Modes Sequential Read/ Write The file is an accumulation of data stored on the disk created by the user.
Operations Binary and ASCII Files Random Access Operation The programmer assigns the file name, the file names are unique and are
Command Line Arguments - Exception Handlings : Principles of used identify the file. No two files can have the same name in the same
Exception Handling The Keywords try, Throws and Catch Exception directory.
Handling Mechanism Multiple Catch Statements Catching Multiple There are various types of files such as text file, program file, data file and
Exceptions Re-throwing Exception Strings: Declaring and Initializing executable files.
String Objects Strings Attributes Miscellaneous Functions.
Data files constrain a combination of number, alphabets, symbols etc.,
Data communication can be performed between program and output
TEXT BOOK devices or files and programs.
1. Ashok N Kamthane, Oriented Programming with ANSI and File stream are used to perform the communication.
Turbo Pearson Education Publications, 2006.
The Stream is nothing but flow of data in bytes in sequence.
The input stream brings data to the program and the output stream collect
data from the program..
Prepared by: Dr. M.Soranamageswari
File Buffer
5.1 File Stream Classes: File Buffer used to accomplished input and output operations with
files.
The io functions of the class istream and ostream invoke the file-buf
Stream is nothing but flow of data..In oops the streams are controlled using function to perform the insertion and extraction on the streams.
classes.
The operations with the files are mainly of two types Fstream Base
There are read and write. It act as a base class for fstream, ifstream and ostream classes.
The ios class is the base class all other classes are derived from ios class.
This classes contain several member function to perform input and output
operation. Ifstream
The istream and ostream classes control input and output functions It is derived from fstream base class it can access the member
respectively. function such as get(), getline(), seekg(), tellg() and read().
The function get(), getline(), read() and >> or defined in the istream class.
The function put(), write() and << are defined in the ostream class. Ofstream
The class ifstream and ofstream are derived from istream and ostream This classes derived from fstream base and ostream class.
classes respectively.
It can access the member function such as put(),seekp(), tellp() and
The header file fstream.h contains the declaration of ifstream and ofstream write().
classes.
Fstream
File Name:
It allows simultaneous input and output operations on a file buffer.
The file name can be a sequence of characters called as streams.
FSTREAM invoke the member function getline() to read() the
characters from the file. String are always declared with character array using file name a file
is recognized.
Steps of File Operations
The length of file depends on the operating system.
The file operation invokes the following basic activities
Normally it is eight characters.
1. File name
A file name also contain extension of 3 characters.
2. Opening file
The extension is optional
3. Reading (or) writing file
Svcc.txt
4. Detecting error
Prg.cpp
5. Closing the file
Test.tat
Invalid file name specified by the programmer. An executable program that performs a specific task for operating
system is called a command .
An attempt to write data to the file that is opened in read only The commands are issued from the command prompt of os.
mode. Some arguments are associated with command called as command
A file opened may already opened by another programs. line arguments.
These arguments are passed to the program.
An attempt to opened read only file for writing operation. In c++ every program start with a main() function.
Device error. The main()function does not contain any arguments
In command line arguments the main() function can receive two
arguments.
1.argc-argument counter it contains the number of arguments
2.argv-argument vector it is an array of character pointers.
Syntax:
in.open(argv[1],ios::in,ios::nocreate);
Main(int argc,char *argv[])
if(in.fail())
Example:
{
#include<stdio.h> cout \n file not found;
#include<fstream.h> exist(0);
#include<conio.h> }
#include<process.h> in.close();
main(int argc, char *argv[]) out.open(argv[2],ios::in,ios::nocreate);
{ if(out.fail())
fstream out; {
ifstream in; rename(argv[1],argv[2]);}
else
if(argc<3)
cout \
{
return 0;
cout
}
exist(1);
}
Example:
#include<iostream.h> Overloading Of Template Function:
#include<conio.h>
Template class<T>
void show(T x) A Template function also supports overloading mechanism.
{
It can be overloaded by normal function or template function
cout<<x;
} No implicit conversion is carried out in parameters of template
void main() function.
{ The rules are,
Search for accurate match of function, if found it is invoked
int i=100;
float f=10.5; Search for a template function with accurate match can be
show( c); generated if found it is invoked
show(i); Attempt normal overloading declaration for the function
show(f);
Incase of no match found error will be reported
}
# include< iostream.h >
#include < conio.h > Class Template With Overloaded Operator:-
template < class T >
The template class permits to declare overloaded operators and member
void show (T a)
function.
{
Creating overloaded operator function is similar to class template members
cout << a;
and functions.
}
#include<iostream.h>
void show (int x)
{ #include<conio.h>
cout <<x; #include<class T>
} class num
void main( ) {
} private:
tnumber;
show(10); public:
show(10.5); num()
}
{
number=0; }
void input()
{
cin>.number;
}
num operator +(num); void main()
void show()
{
{
cout<<number; num<int>n1,n2,n3;
} N1.input;
}; N2.input;
Template<class T>
num<T> num<T>::Operator+(num<T>) N3.show();
{ }
num<T> temp;
Tmp.number=number+c.number;
return(temp);
}
Class Templates And Inheritance:
While writing large programs a programmer makes many Exceptions are two types
mistakes developing an error free program is the objective of 1.synchronous exception
the programmer. 2.Asynchronous exception
Programmer have to take care to prevent errors. The goal of exception handling is to create a routine that detect and
Errors can be trapped using exception handling features. an exceptional condition is order to execute suitable action.
An Exception is an up normal terminator of a program, which The routine carries the following responsibilities:
is executed in a program at run-time or it may called at run- 1. Detect the problem
time when an error occurs the exception contains warning 2. Warning message indicates an error.
messages like invalid argument insufficient memory, division 3. Accept the error message.
4. Perform the accurate action.
An Exception is an object , it is sent from the part of the program
where an error occurs to that part which is going to control the error.
try
if(j=0)
{
throw j; sub(8,5);
else sub(0,5);
cout - \ }
} catch(int)
catch(int)
{
{
cout \ cout \
throw; }
} cout \
cout \n\ getch();
}
int main()
}
{
cout \n inside function main()\
5.15 Declaring and Initializing String Objects: 4.Strcmp();
Example:
1. Strlen()
Srtcmp(str1,str2);
2. strcpy() 5)stricmp();
Syntax: Example
Strcpy(destination ,source) i=stricmp(Str1,Str2)
Example: 6)Strncmp();
Strcpy(b,a) Example
Set=strncmp(Str1,Str2,4);
3.strncpy
7)Strnicmp();
Syntax: Example
Char*strncpy(char*desk, const char *src, size t n) j=strnicmp(Str1,Str2,5);
Example: 8)Strlwr();
Strncpy(dest,src,10); Example
Strlwr(Str1);
13)StrStr()
9)Strupr();
Example:
Example
Strupr(Str1); Set=strstr(traystack,needle);
10)Strdup():- 14) strncat()
Example:
Example
Strncat
P2=Strdup(p1);
11) Strchar(); 15) strset()
Example Example:
Strset(str
Set=Strchr(Str,ch);
12) Strrchar();
Example
Set=strrchar(Str,ch);