Oops Notes
Oops Notes
ORIENTED
PROGRAMMING
UNIT- 1
2
INTRODUCTION (OOP’s) :-
• Object-oriented programming (OOP) is a programming paradigm
based on the concept of "objects", which can contain data, in the form
of fields (often known as attributes or properties), and code, in the
form of procedures (often known as methods). A feature of objects is an
object's procedures that can access and often modify the data fields
of the object with which they are associated (objects have a notion of
"this" or "self").
3
DEFINATION :-
• In this way, the data structure becomes an object that includes both data and
functions. In addition, programmers can create relationships between one object
and another. For example, objects can inherit characteristics from other objects.
4
The problem with procedure oriented programming are :-
5
Polymorphism :- The word polymorphism means having many forms.
In simple words, we can define polymorphism as the ability of a message to be
displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the
same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The
behaviour depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading:-
• Operator Overloading: The process of making an operator to exhibit
different behaviours in different instances is known as operator overloading.
6
Class: - The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds its own
data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.
Example: - Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the
class and wheels, speed limits, mileage are their properties.
• A Class is a user-defined data-type which has data members and member
functions.
• Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions define the properties and behaviour of the
objects in a Class.
• In the above example of class Car, the data member will be speed limit,
mileage etc and member functions can apply brakes, increase speed etc.
Object take up space in memory and have an associated address like a record
in Pascal or structure or union in C.
7
When a program is executed the objects interact by sending messages to one
another.
Each object contains data and code to manipulate the data. Objects can
interact without having to know details of each other’s data or code, it is
sufficient to know the type of message accepted and type of response returned
by the objects.
Encapsulation: - Encapsulation is defined as wrapping up of data and
information under a single unit. In Object-Oriented Programming,
Encapsulation is defined as binding together the data and the functions that
manipulate them.
8
• Abstraction in Header files: One more type of abstraction in C++ can be
header files. For example, consider the pow () method present in math.
header file. Whenever we need to calculate the power of a number, we
simply call the function pow () present in the math. Headers file and pass
the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.
• Sub Class: The class that inherits properties from another class is called
Sub class or Derived Class.
• Super Class: The class whose properties are inherited by sub class is
called Base Class or Super class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
9
Dynamic Binding: In dynamic binding, the code to be executed in
response to function call is decided at runtime. C++ has virtual functions to
support this.
2. CHARACTERISTICS OF OOP’s :-
10
Encapsulation: The technical term for combining data and functions
together as a bundle is an encapsulation.
11
and make them operate on different data types in other words over
loading the existing functionality with the new one. This is a very
important feature of object-oriented programming methodology which
extended the handling of data type and operations.
b. Data Redundancy :-
This is a condition created at the place of data storage (you can say
Database where the same piece of data is held in two separate places. So
the data redundancy is one of the greatest advantages of OOP. If a user
wants a similar functionality in multiple classes he/she can go ahead by
writing common class definitions for the similar functionalities and inherit
them
c. Code Maintenance:-
This feature is more of a necessity for any programming languages, it helps
users from doing re-work in many ways. It is always easy and time-saving to
maintain and modify the existing codes with incorporating new changes into
it.
12
d. Security :-
With the use of data hiding and abstraction mechanism, we are filtering out
limited data to exposure which means we are maintaining security and
providing necessary data to view.
e. Design Benefits:-
If you are practicing on OOPs the design benefit a user will get is in terms of
designing and fixing things easily and eliminating the risks (if any). Here the
Object Oriented Programs forces the designers to have a longer and
extensive design phase, which results in better designs and fewer flaws.
After a time when the program has reached some critical limits, it is easier to
program all the non-OOP’s one separately.
f. Better productivity:-
With the above-mentioned facts of using the application definitely enhances
its users overall productivity. This leads to more work done, finish a better
program, having more inbuilt features and easier to read, write and maintain.
An OOP programmer cans stitch new software objects to make completely
new programs. A good number of libraries with useful functions in
abundance make it possible.
g. Easy troubleshooting :-
lets witness some common issues or problems any developers face in their
work.
So, many a time it happens that something has gone wrong which later
becomes so brainstorming for the developers to look where the error is. Relax!
Working with OOP language you will know where to look for. This is the
advantage of using encapsulation in OOP; all the objects are self-
constrained. With this modality behavior, the IT teams get a lot of work benefits
as they are now capable to work on multiple projects simultaneously with an
advantage that there is no possibility of code duplicity.
13
APPLICATION OF OOP’S ARE :
a. Client-Server Systems
b. Object-Oriented Databases
They are also called Object Database Management Systems (ODBMS). These
databases store objects instead of data, such as real numbers and integers.
Objects consist of the following:
Attributes: Attributes are data that defines the traits of an object. This data
can be as simple as integers and real numbers. It can also be a reference to a
complex object.
Methods: They define the behavior and are also called functions or
procedures.
14
d. Real-Time System Design
Real time systems inherit complexities that makes difficult to build them.
Object-oriented techniques make it easier to handle those complexities. These
techniques present ways of dealing with these complexities by providing an
integrated framework which includes schedulability analysis and behavioral
specifications.
OOP also helps in laying out a framework for Hypertext. Basically, hypertext is
similar to regular text as it can be stored, searched, and edited easily. The only
difference is that hypertext is text with pointers to other text as well.
15
h. Office Automation Systems
i. Email
j. Word processing
k. Web calendars
l. Desktop publishing
m. CIM/CAD/CAM Systems
n. AI Expert Systems
16
DIFFRENCE BETWEEN CLASS AND OBJECT :
17
UNIT- 2
18
1. BASIC DATA TYPES (C++) :-
19
Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to
2147483647.
Character: Character data type is used for storing characters. Keyword
used for character data type is char. Characters typically requires 1 byte
of memory space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical
values. A Boolean variable can store either true or false. Keyword used
for Boolean data type is bool.
Floating Point: Floating Point data type is used for storing single
precision floating point values or decimal values. Keyword used for
floating point data type is float. Float variables typically requires 4 byte of
memory space.
Double Floating Point: Double Floating Point data type is used for
storing double precision floating point values or decimal values. Keyword
used for double floating point data type is double. A double variable
typically requires 8 byte of memory space.
void: Void means without any value. void data type represents a
valueless entity. Void data type is used for those functions which do not
return a value.
Wide Character: Wide character data type is also a character data
type but this data type has size greater than the normal 8-bit data type.
Represented by wchar_t. It is generally 2 or 4 bytes long.
Derived Data Types: The data-types that are derived from the
primitive or built-in data types are referred to as Derived Data Types.
These can be of four types namely:-
• Function
• Array
• Pointer
• Reference
Function: A function is a block of code or program-segment that is
defined to perform a specific well-defined task. A function is generally
defined to save the user from writing the same lines of code again and
again for the same input. All the lines of code are put together inside a
single function and this can be called anywhere required. main() is a
default function that is defined in every program of C++.
20
Syntax:-
FunctionType FunctionName(parameters)
Example:-
Output: // C++ program to demonstrate
// Function Derived Type
#include <iostream>
using namespace std;
// max here is a function derived type
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
// main is the default function derived type
int main()
{
m = max(a, b);
int a = 10, b = 20;
// Calling above function to
// find max of 'a' and 'b'
int cout << "m is " << m;
return 0;
}
Output:-
m is 20
Array: An array is a collection of items stored at continuous memory
locations. The idea of array is to represent many instances in one
variable.
21
Syntax:-
DataType ArrayName[size_of_array];
Example:-
// C++ program to demonstrate
// Array Derived Type
#include <iostream>
using namespace std;
int main()
{
// Array Derived Type
int arr[5];
arr[0] = 5;
arr[2] = -10;
// this is same as arr[1] = 2
arr[3 / 2] = 2;
arr[3] = arr[0];
cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];
return 0;
}
Output:-
5 2 -10 5
22
Pointers: Pointers are symbolic representation of addresses. They
enable programs to simulate call-by-reference as well as to create and
manipulate dynamic data structures. It’s general declaration in C/C++ has
the format :
Syntax:
datatype *var_name ;
Example:-
// C++ program to illustrate
// Pointers Derived Type
#include <bits/stdc++.h>
using namespace std;
void geeks()
{
int var = 20;
// Pointers Derived Type
// declare pointer variable
int* ptr;
// note that data type of ptr
// and var must be same
ptr = &var;
// assign the address of a variable
// to a pointer
cout << "Value at ptr = "
<< ptr << "\n";
cout << "Value at var = "
<< var << "\n";
cout << "Value at *ptr = "
23
<< *ptr << "\n";
}
// Driver program
int main()
{
geeks();
}
Output:-
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20
Value at *ptr = 20
Example:-
// C++ program to illustrate
// Reference Derived Type
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// Reference Derived Type
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
24
ref = 20;
cout << "x = " << x << endl;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl;
return 0;
}
Output:
x = 20
ref = 30
User-Defined Data Types : The data types that are defined by the
user are called the derived data type or user-defined derived data type.
25
Syntax:-
Example:-
// C++ program to demonstrate
// Class
#include <bits/stdc++.h>
using namespace std;
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};
int main()
26
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
obj1.geekname = "GeeksForGeeks";
// accessing member function
obj1.printname();
return 0;
}
Output:-
Geekname is: GeeksForGeeks
Example:-
// C++ program to demonstrate
// Structures in C++
#include <iostream>
using namespace std;
struct Point {
27
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = 20;
cout << arr[0].x << ", " << arr[0].y;
return 0;
}
Output:-
10, 20
Union:- Like Structures , union is a user defined data type. In union, all
members share the same memory location. For example in the following
C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.
Example:-
#include <iostream>
using namespace std;
// Declaration of union is same as the structures
union test {
int x, y;
};
int main()
{
// A union variable t
28
union test t;
// t.y also gets value 2
t.x = 2;
cout << "After making x = 2:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
// t.x is also updated to 10
t.y = 10;
cout << "After making Y = 10:"
<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;
return 0;
}
Output:-
After making x = 2:
x = 2, y = 2
After making Y = 10:
x = 10, y = 10
Syntax:-
enum State {Working = 1, Failed = 0};
29
Example:-
// Program to demonstrate working
// of enum in C++
#include <iostream>
using namespace std;
enum week { Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun };
int main()
{
enum week day;
day = Wed;
cout << day;
return 0;
}
Output:-
2
Typedef :- C++ allows you to define explicitly new data type names by
using the keyword typedef. Using typedef does not actually create a new
data class, rather it defines a name for an existing type. This can increase
the portability (the ability of a program to be used across different types of
machines; i.e., mini, mainframe, micro, etc; without much changes into
the code)of a program as only the typedef statements would have to be
changed. Using typedef one can also aid in self-documenting code by
allowing descriptive names for the standard data types.
30
Syntax:-
Where type is any C++ data type and name is the new name for this data
type.
This defines another name for the standard type of C++.
Example:-
// C++ program to demonstrate typedef
#include <iostream>
using namespace std;
// After this line BYTE can be used
// in place of unsigned char
typedef unsigned char BYTE;
int main()
{
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
Output:-
C
Data modifiers: - data type modifiers are used with the built-in data
types to modify the length of data that a particular data type can hold.
31
SIZE (IN
DATA TYPE BYTES) RANGE
Float 4
Double 8
long double 12
32
2. TYPE COMPATIBILITY (C++) :-
C++ is very strict with regard to type compatibility as compared to C. Type
compatibility is very close to automatic or implicit type conversion. The type
compatibility is being able to use two types together without modification and
being able to substitute one for the other without modification.
The type compatibility is categorized into following three types by the
compiler:-
float n1=12.5;
int n2=n1;
This assigning of float value to int type will result in loss of decimal value of
n1. However, this type compatibility will not show any error but it might give a
warning “possible loss of data”.
Expression compatibility:-
Here the result will be 1. The actual result of 3/2 is 1.5 but because of
incompatibility there will be loss of decimal value.
33
For example:-
void show(int n)
{
cout<<”n=”<<n;}
void main()
{
show(8.2);
}
Here output will be n=8 due to incompatibility in actual and formal parameter
type.
3. OPERATORS IN C++
What is an operator?
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators and
provide the following types of operators –
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
34
Arithmetic Operators :-
Assume variable A holds 10 and variable B holds 20, then :-
Relational Operators:-
Logical Operators:-
Assume variable A holds 1 and variable B holds 0, then :-
36
Bitwise Operators:-
Bitwise operator works on bits and performs bit-by-bit operation. The truth
tables for &, |, and ^ are as follows –
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
37
Assume variable A holds 60 and variable B holds 13, then :-
38
Assignment Operators :-
Operator Description Example
39
Misc Operators:-
Sr.No Operator & Description
1 size of
size of operator returns the size of a variable. For example,
sizeof(a), where ‘a’ is integer, and will return 4.
2 Condition? X : Y
Conditional operator (?). If Condition is true then it returns value of
X otherwise returns value of Y.
3 ,
Comma operator causes a sequence of operations to be performed.
The value of the entire comma expression is the value of the last
expression of the comma-separated list.
5 Cast
Casting operators convert one data type to another. For example,
int(2.2000) would return 2.
6 &
Pointer operator & returns the address of a variable. For example
&a; will give actual address of the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will
pointer to a variable var.
Syntax:-
Condition ? Expression2 : Expression3;
40
Operators Precedence in C++ :-
41
4. SCOPE RESOLUTION OPERATOR (C++) :-
Output:-
Value of global x is 0
Value of local x is 10
42
{
public:
// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun()
{
cout << "fun() called";
}
int main()
{
A a;
a.fun();
return 0;
}
Output:-
fun() called
44
// Use of scope resolution operator in multiple inheritance.
#include<iostream>
using namespace std;
class A
{
protected:
int x;
public:
A() { x = 10; }
};
class B
{
protected:
int x;
public:
B() { x = 20; }
};
class C: public A, public B
{
public:
void fun()
{
cout << "A's x is " << A::x;
cout << "\nB's x is " << B::x;
}
};
int main()
{
C c;
c.fun();
return 0;
}
45
Output :-
A's x is 10
B's x is 20
• For namespace: - If a class having the same name exists inside two
namespace we can use the namespace name with the scope resolution
operator to refer that class without any conflicts.
// Use of scope resolution operator for namespace.
#include<iostream>
int main(){
std::cout << "Hello" << std::endl;
}
Output :-
Here, cout and endl belong to the std
namespace.
47
There are 4 types of control structures are as follows:-
• Sequence structure
• Selection structure
• Repetition structure
• Functional call structure
IF Statement
IF...ELSE Statement
SWITCH Statement
IF statement: - When you use the “if “statement, you check a condition.
If the condition is met (true), a piece of code is executed. However if the
condition is false, the piece of code in the loop body is skipped.
48
Syntax:-
if (condition)
;
{
Statement 1;
}
Statement 2;
Statement 3;
Example:-
int main()
{
int age;
age = 70;
if (age>60)
{
cout<<”Incorrect age”<<endl;
}
return 0;
}
Output:-
Incorrect age
49
Syntax:-
if (condition)
{
Statement 1;
}
else
{
Statement 2;
}
Statement 3;
Example:-
Let’s enhance the example of the “if” statement. Now, when the condition
(age< 60) is true we display the message “correct age”, and when the
condition is false we display the message “incorrect age”:
int main()
{
int age;
age = 70;
if (age<=60)
{
cout<<”Correct age”<<endl;
}else
{
cout<<”Incorrect age”<<endl;
}
return 0;
}
50
Output:-
Incorrect age
Example:-
int main()
{
int x=0;
while(x<=5)
{
cout<<x<<endl;;
x=x+1;
}
return 0;
}
Output:-
0
1
2
3
4
5
52
Understanding the statements of the above program:33339999999
Syntax:-
int main()
{
int x=0;
while(x<=5)
{
cout<<x<<endl;;
x=x+1;
}
return 0;
}
53
Output:-
0
1
2
3
4
5
FOR Loop:- A “for” loop, like other loop structures, executes a piece of
code as many times as you want. You use a “for” loop when you know the
number of times you want to execute a piece of code.
Syntax:-
for(initial value; condition; increment)
{
Statement1;
}
Statement 2;
54
UNIT - 3
55
FUNCTION C++
Syntax
56
Illustration of function call
Let’s suppose the function is stored at the address 0x111. When we call the
function in the main program compiler goes to that memory location 0x111
where the code is executed as defined.
After the execution, the compiler returns the result to the program without
concerning any details how the result was obtained.
Though it takes time for execution, it becomes handy when dealing with
huge programs.
57
General structure of a function in C++ program
namespace std;
main()
........
........
........
function definition
........
58
FUNCTION PROTOTYPING:-
While writing a program, we can’t use a function without specifying its type
or without telling the compiler about it.
Syntax
return_type function_name(parameter_list);
Here, return_type is the type of value that the function will return. It can be
int, float or any user-defined data type.
59
CALL BY REFERENCE:-
int temp;
x = y; /* put y into x */
60
For now, let us call the function swap() by passing values by reference as
in the following example −
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is put together in a file, compiled and executed, it
produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
61
INLINE FUNCTION:-
C++ inline function is powerful concept that is commonly used with classes.
If a function is inline, the compiler places a copy of the code of that function
at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once
again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler
can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
Following is an example, which makes use of inline function to return max
of two numbers −
#include <iostream> using
namespace std; inline int
Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
62
FUNCTION OVERLOADING:-
When we have multiple functions with the same name but different
parameters, then they are said to be overloaded. This technique is used to
enhance the readability of the program.
There are two ways to overload a function, i.e. −
Standard C++ Library incorporates all the Standard C libraries also, with
small additions and changes to support type safety.
64
UNIT – 4
65
COMPARISON OF CLASS AND C- STRUCTURE :-
Comparison Chart:-
BASIS FOR
STRUCTURE CLASS
COMPARISON
Requires No Yes
constructor and
destructor
66
Structure: - A structure is a collection of variables of dissimilar data
types, all referenced by one name. A structure declaration forms a template
that is used to create an instance of the structure.
Syntax:-
struct sname
{
type struct_element1;
type struct_element2;
type struct_element3;
.
}
variable1, variable2, . .
;
The keyword ‘struct’ defines to the compiler that a structure is being declared.
The ‘sname’ represents the name given to the structure. The structure
declaration is always terminated by a semicolon, as it is considered as a
statement.
You can declare the instances of the structure before its termination as done
in above code (variable1, variable2) or you can declare the instance of
structure in main( ), by writing the instance name preceded with the name of
the structure.
67
Example:-
#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;
/*Assigning the values of each struct member here*/
student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;
/* Displaying the values of struct members */
printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
Output:-
68
Class: - Class in OOP defines a new type which contains data members
and member function, that are used to access the data members of the class.
The instances of classes are called “objects” each of which has the same
organization as a class. The class is a logical abstraction, whereas an object
has a physical existence.
Syntax:-
class Class_Name
{
Private:
Data-Type Variable_Name;
Function declaration or Function
Definition;
Public:
Data-Type Variable_Name;
Function declaration or Function
Definition;
};
Here, the class is a keyword which declares to the compiler that a class has
been declared. The main feature of OOP is data hiding which is
accomplished by providing three access specifiers that are “public”, “private”,
“protected”. If you do not specify any access specifier in the class while
declaring data members or member functions, by default all are considered
private.
69
Example:-
class test
{
int a, b;
public:
void input ();
{
cout<<"Enter Value of a and b";
cin>>a>>b;
}
void output ()
{
cout<<"A="<<a<<endl<<"B="<<b;
}
};
Key Differences between Structure and Class:-
1. The main difference between structures and classes is that by default,
all member of the structure are public. In contrast, by default, all the
members of the class are private.
2. A structure is considered as the value type whereas; a class is a
reference type.
3. At the time of instantiating a structure, the memory is allocated on a
stack. As against, in class, the memory is allotted on the heap.
4. No structure member can have a null value. Conversely, the variables
of a class can have null values.
5. In order to initialize the member of a class, the constructors and
destructors are used. On the contrary, the structure can initialize its
members automatically.
6. In variables in the structure can not be initialized during the declaration
while in case of class, this can be done.
Similarities:-
• In C++, both the structure and class are syntactically equivalent.
• Both structure and class can declare some of their members private.
• The name of a structure or class can be used as a stand-alone type.
• Both structure and class support the mechanism of inheritance.
70
CREATING OBJECTS:-
There are two different methods for creating objects of the class:-
(1) We can create object at the time of specifying a class after the
closing curly bracket.
Example:-
Class test
{
int a,b;
public:
void input ();
void ouput ();
}t1,t2,t3;
Here, t1, t2 and t3 are the objects of class test.
(2) We can create object inside the main function using name of the
class.
The general syntax for creating object inside main function is as below:
Class_Name Object_Name;
Example:-
Test t1, t2, t3;
Here, t1, t2 and t3 are the objects of class test.
71
How to Access Class Members?
The data member and member function declared as a public can be accessed
directly using the object of the class. But the data member and member
function declared as private cannot be accessed directly using the object of
the class.
We can access private member of the class using public member of the
class.
The general syntax for accessing public member using object is given below:-
72
ARRAYS WITHIN CLASS :-
• Arrays can be declared as the members of a class.
• The arrays can be declared as private, public or protected members of the
class.
• To understand the concept of arrays as members of a class, consider this
example.
Example -1:-
#include<iostream>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
};
void student :: getdata ()
{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating total marks
{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}
void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}
73
Output:-
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
Example-2:-
#include<iostream.h>
class arraydemo
{
int a[6];
public:
void getelts()
{
cout<<”Enter 6 numbers in the array:”<<endl;
for(int i=0;i<6;i++)
{
cin>>a[i];
}
}
void show()
{
cout<<”\nArray elements are”<<endl;
for(int i=0;i<6;i++)
{
cout<<a[i]<<endl;
}
}
};
void main()
{
arraydemo obj;
obj.getelts();
obj.show();
}
74
Output:-
Enter 6 numbers in the array:
5
6
2
1
7
4
9
Array elements are
5
6
2
1
7
4
9
ARRAYS OF OBJECT:-
Like data member of the class we can also create an array of objects.
Array of object is useful when we want to create large number of objects of the
same class.
• Like array of other user-defined data types, an array of type class can also
be created.
• The array of type class contains the objects of the class as its individual
elements.
• Thus, an array of a class type is also known as an array of objects.
• An array of objects is declared in the same way as an array of any built-in
data type.
75
Syntax (array of object) :-
class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;
method1();
method2();
----------
methodN();
};
class-name obj[ size ];
Example -1:-
#include<iostream.h>
class Student
{
int rollno;
char name[20];
public:
void Input();
void Output();
};
void Student::Input()
{
cout<<"Enter Roll Number:";
cin>>rollno;
cout<<"Enter Name:";
cin>>name;
}
void Student::Output()
{
cout<<"Roll Number:"<<rollno<<endl;
cout<<"Name:"<<name<<endl;
}
int main()
{
Student S[3];
76
int i;
for(i=0;i<3;i++)
S[i].Input();
for(i=0;i<3;i++)
S[i].Output();
return 0;
}
Output:-
In above example we create an array of object using following statement:
Student S [3]; Here, we create 3 objects. First object refer to S [0], second
object refer to S[1] and third object refer to S[2].
Thus in array of object an object can be identified using the name of the array
and index.
77
Example -2:-
#include <iostream>
class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};
void main()
{
MyClass obs[4];
int i;
for(i=0; i < 4; i++)
obs[i].setX(i);
for(i=0; i < 4; i++)
cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";
getch();
}
Output:-
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
78
Example-3:-
#include<iostream.h>
#include<conio.h>
class Employee
{
int Id;
char Name[25];
int Age;
long Salary;
public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"\n\tEnter Employee Id : ";
cin>>Id;
cout<<"\n\tEnter Employee Name : ";
cin>>Name;
cout<<"\n\tEnter Employee Age : ";
cin>>Age;
cout<<"\n\tEnter Employee Salary : ";
cin>>Salary;
}
void PutData() //Statement 2 : Defining PutData()
{
cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary;
}
};
void main()
{
int i;
Employee E[3]; //Statement 3 : Creating Array of 3 Employees
for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
E[i].GetData();
}
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();
}
79
Output:-
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee
using array of object. Statement 1 is creating an array of Employee Emp to
store the records of 3 employees.
80
OBJECTS AS FUNCTION ARGUMENT:-
In C++ we can pass object as a function argument and also return an object
from the function.
Example -1:-
#include<iostream.h>
class Demo
{
int a,b;
public:
Demo()
{
a=0;
b=0;
}
Demo(int x, int y)
{
a=x;
b=y;
}
void display()
{
cout<<"A="<<a<<endl<<"B="<<b<<endl;
}
Demo sum(Demo D2);
};
Demo Demo::sum(Demo D2)
{
81
Demo D3;
D3.a = a + D2.a;
D3.b = b + D2.b;
return D3;
}
int main()
{
Demo B1(1,2);
Demo B2(3,4);
Demo B3;
B3 =B1.sum(B2);
B3.display();
return 0;
}
Output:-
A=4
B=6
Above program performs the addition of data member of two objects and store
it in the third object.
Consider the function defined inside class:
#include<iostream.h>
class time
{
int hr,min;
public:
void gettime(int h,int m)
{
hr=h;
min=m;
}
void puttime(void)
{
cout<<hr<< “ hrs and “;
cout<<min<<” mins “<<endl;
}
void sum(time, time); //declaration of function with object as
argument
};
void time :: sum(time t1, time t2)
{
min=t1.min+t2.min;
hr=min/60;
min=min%60;
hr=hr+t1.hr+t2.hr;
}
83
int main()
{
time obj1,obj2, obje3;
obj1.gettime(2, 45);
obj2.gettime(3, 30);
obj3.sum(obj1,obj2); //obj3=obj1+obj2;
cout<<” obj1= “;
obj1.puttime();
cout<<”obj2= “;
obj2.puttime();
cout<<”obj3= “;
obj3.puttime();
return 0;
}
Output:-
An object can also be passed to the non member functions, however this non
member function cannot access the private data members of the class and
can access only public member functions through the object passed as
argument.
84
UNIT – 5
85
Constructor and Destructor
INTRODUCTION
C++ allows different categories of data types, that is, built-in data types
(e.g., int, float, etc.) and user defined data types (e.g., class). We can
initialize and destroy the variable of user defined data type (class), by
using constructor and destructor in object oriented programming .
Constructor is used to create the object in object oriented programming
language while destructor is used to destroy the object. The constructor
is a function whose name is same as the object with no return type. The
name of the destructor is the name of the class preceded by tilde (~).
First we will discuss briefly about constructor and destructor and then
move on to the types of constructor and memory management.
Whenever an object is created, the special member function , that is,
constructor will be executed automatically . Constructors are used to
allocate the memory for the newly created object and they can be
overloaded so that different form of initialization can be accommodated.
If a class has constructor , each object of that class will be initialized . It is
called constructor because it constructs the value of data members of
the class.
86
Example: A constructor is declared and defined as follows:
Characteristics of Constructors:-
A constructor for a class is needed so that the compiler automatically
initializes an object as soon as it is created . A class constructor if defined
is called whenever a program creates an object of that class The
constructor functions have some special characteristics which are as
follows:
• They should be declared in the public section.
• They are invoked directly when an object is created.
• They don’t have return type, not even void and hence can’t return
any values.
• They can’t be inherited; through a derived class, can call the base
class constructor.
• Like other C++ functions, they can have default arguments.
• Constructors can’t be virtual.
• Constructor can be inside the class definition or outside the class
definition.
• Constructor can’t be friend function.
• They can’t be used in union.
• They make implicit calls to the operators new and delete when
memory allocation is required.
87
Limitations of Constructor
Parameterized Constructor:-
We can write a constructor in C++ which can accept parameters for its
invocation. Such constructor that can take the arguments are called
parameterized constructor. In other words; “Declaring a constructor with
arguments hides the default constructor”. This means that we can
always specify the arguments whenever we declare an instance of the
class.
To illustrate parameterized constructor well, let us write the syntax and take
one example:
class <cname>
{
//data
public: cname(arguments); // parameterized constructor
.........
.........
};
Examples:
class student
{
char name[20]; int rno;
public: student(char,int); //parameterized constructor
};
student :: student(char n,int r)
{
name=n; rno=r;
}
88
Multiple constructor in a class:-
A class can have multiple constructors that assign the fields in different
ways . Sometimes it's beneficial to specify every aspect of an object 's data
by assigning parameters to the fields, but other times it might be
appropriate to define only one or a few.
Copy Constructor:-
Sometimes it is required to copy the value of data member of one object
into another object while creating it. This can be accomplished using the
concept of copy constructor.
The constructor that accepts reference to the object as an argument is
known as copy constructor.
A copy constructor is used to declare and initialize an object from another
object. For example, the statement integer 12(11);
would define the object 12 and at the same time initialize it to the value of
11. Another form of this statement is integer 12 = 11;
Thus the process of initializing through a copy constructor is known as copy
initialization.
A copy constructor is always used when the compiler has to create a
temporary object of a class object. The copy constructors are used in the
following situations
• The initialization of an object by another object of the same class.
• Return of objects as a function value.
• Stating the object as by value parameters of a function.
89
The syntax of copy constructor is: class_name :: class_name(class_name
&ptr)
Class Rectangle
Height, Width;
Rectangle (Rectangle &r)
int Height
Width = r.Width;
}
}
class <cname>
{
//data
public: cname(arguments); // parameterized constructor
};
Examples:
class student
{
char name[20];
int rno;
public: student(char,int); //parameterized constructor
};
student :: student(char n,int r)
{
name=n;
rno=r;
}
90
Program has been given below:
#include<iostream>
#include<conio.h>
using namespace
std; class student
{
int roll;
char
name[30];
public:
student() // default constructor
{
roll =10;
strcpy(name,"x"
);
}
student( student &O) // copy constrcutor
{
roll =O.roll;
strcpy(name,
O.name);
}
void input_data()
{
cout<<"\n Enter roll no :"; cin>>roll;
cout<<"\n Enter name :";
cin>>name;
}
void show_data()
{
cout<<"\n Roll no :"<<roll;
cout<<"\n Name
:"<<name;
}
};
int main()
{
student s; // default construtor
s.show_data();
student A(s); // copy constructor
A.show_data(
); getch();
return 0;
}
91
Constructor Overloading:-
When more than one constructor function is defined in a class, then it is
called constructor overloading or use of multiple constructor in a class. It is
used to increase the flexibility of a class by having more number of
constructors for a single class.
Overloading constructors in C++ programming gives us more than one way
to initialize objects in a class.
To illustrate the constructor overloading, let us take following examples:
92
DESTRUCTORS
#include<iostream.h>
#include<conio.h>
} };
main()
// s1 is an object
getch();
93
Program:
#include<iostream>
#include<conio.h>
using namespace std;
class xyz
{
public:
xyz()
{
cout<<"\n Constructor ";
}
~xyz() // use of destructor with -- tilde
{
cout<<"\n Destructor ";
}
};
int main()
{
{
xyz B;
}
getch();
return 0;
}
94
PROGRAMS ON CONSTRUCTOR & DESTRUCTOR
#include<iostream.h>
#include<conio.h> class stu
{
private: char name[20],add[20]; int roll,zip;
public: stu ( );//Constructor
~stu( );//Destructor void read( );
void disp( );
};
stu :: stu( )
{
cout<<”This is Student Details”<<endl;
}
void stu :: read( )
{
cout<<”Enter the student Name”; cin>>name;
cout<<”Enter the student roll no “; cin>>roll;
cout<<”Enter the student address”; cin>>add;
cout<<”Enter the Zipcode”; cin>>zip;
}
void stu :: disp( )
{ cout<<”Student Name :”<<name<<endl; cout<<”Roll no is :”<<roll<<endl;
cout<<”Address is :”<<add<<endl; cout<<”Zipcode is :”<<zip;
}
stu : : ~stu( )
{
cout<<”Student Detail is Closed”;
}
void main( )
{
stu s; clrscr( );
s.read ( );
s.disp ( );
getch( );
}
95
Output:
Sushil
01
Delhi
110092
Roll no is : 01
Address is : Delhi
Zipcode is :110092
96
UNIT – 6
97
Operator Overloading in C++:-
The process of giving special meaning to the existing c++ operator is known
as "Operator Overloading".
Using the concept of operator overloading we can use operators with object of
the class.
For example: We can use + to perform addition of two integer or floating point
numbers. In the same way we can overload + operator so that we can perform
addition of two objects of the class.
When you overload the existing operator the basic syntax rules of the operator
is not changed. It remains as it is.
In order to overload particular operator you need to use special function
known as operator function.
98
Unary Operator Overloading:-
Unary operator having one operand so generally we need to pass one
argument to the operator function.
If you define operator function as a member function then it will accept no
argument. Because the object that is used to invoke the operator function is
passed implicitly to the operator function.
If you define operator function as a friend function then it will accept one
argument. Because friend functions is not a member function so it is not
invoked using object of the class. Thus we need to pass object as an
argument explicitly.
Once the operator function is defined you can invoke operator function in
following different ways:
op ObjectName;
or
// For Member Function
ObjectName.operator ();
// For Friend Function
Operator op (ObjectName)
99
Once the operator function is defined you can invoke operator function in
following different ways:
ObjectName1 op ObjectName2;
Or
// For Member Function ObjectName1.operator (ObjectName2);
// For Friend Function
Operator op (ObjectName1, ObjectName2);
Operator Overloading
There are some rules or restrictions for overloading operators. These rules are
as given below:
1. You can overload only existing operator. New operator can not be created.
2. you can not overload following operators:
100
Overload Unary Operator using Member Function
Unary operator having one operand so generally we need to pass one
argument to the operator function.
If you define operator function as a member function then it will accept no
argument. Because the object that is used to invoke the operator function is
passed implicitly to the operator function.
Consider following example to overload unary operator ++ using member
function
#include <iostream.h>
class demo
{
int count;
public:
demo()
{
count=0;
}
void operator ++()
{
count++;
}
void display()
{
cout<<"Count="<<count<<endl;
}
};
int main()
{
demo d1;
++d1;
d1.display();
++d1;
d1.display();
return 0;
}
Output:
Count = 1
Count = 2
101
Overload Unary Operator using Friend Function
If you define operator function as a friend function then it will accept one
argument. Because friend functions is not a member function so it is not
invoked using object of the class. Thus we need to pass object as an
argument explicitly.
Consider following example to overload unary operator ++ using friend
function.
#include <iostream.h>
class demo
{
int count;
public:
demo()
{
count=0;
}
friend void operator ++(demo &d)
{
d.count++;
}
void display()
{
cout<<"Count="<<count<<endl;
}
};
int main()
{
demo d1; operator
++(d1); d1.display();
operator ++(d1);
d1.display(); return 0;
}
Output:
Count = 1
Count = 2
102
Overload Binary Operator using Member Function
Binary operator having two operands so generally we need to pass two
arguments to the operator function.
If you define operator function as a member function then it will accept one
argument. Because the object that is used to invoke the operator function is
passed implicitly to the operator function and other object is passed explicitly
to the function.
Consider following example to overload binary operator + using member
function.
#include <iostream.h> class demo
{
int x,y; public:
demo()
{ x=0;
y=0;
}
demo(int a, int b)
{
x=a; y=b;
}
demo operator +(demo &d)
{
demo d3;
d3.x = x + d.x;
d3.y = y + d.y;
return d3;
}
void display()
{
cout<<"X="<<x<<endl; cout<<"Y="<<y<<endl;
}
};
int main()
{
demo d1(2,3);
103
demo d2(4,5);
demo d
d3 = d1 + d2;
cout<<"Object C1\n";
d1.display();
cout<<"Object C2\n";
d2.display();
cout<<"Object C3\n";
d3.display();
return 0;
}
Output:
Object C1
X=2
Y=3
Object C2
X=4
Y=5
Object C3
X=6
Y=8
104
Overload Binary Operator using Friend Function
If you define operator function as a friend function then it will accept two
arguments. Because friend functions is not a member function so it is not
invoked using object of the class. Thus we need to pass two objects as an
argument explicitly.
Consider following example to overload binary operator + using friend
function.
d3 = operator + (d1,d2);
cout<<"Object C1\n";
d1.display();
cout<<"Object C2\n";
d2.display();
cout<<"Object C3\n";
d3.display();
return 0;
}
Output:
Object C1
X=2
Y=3
Object C2
X=4
Y=5
Object C3
X=6
Y=8
105
Type Conversion in C++:-
In a mixed expression constants and variables are of different data types . The
assignment operations causes automatic type conversions between the
operands as per the rules. The type of data to the right of an assignment
operator is automatically converted to the data type of variable on the left
which is called as the Type Conversion. Example :- int x; float y = 20.123; x =
y;
1. Using constructor
2. Using Operator Overloading
Using Constructor:-
• We can use constructor to perform type conversion during the object
creation.
• Consider the following example with class ‘Time’ in which we want to
assign total time in minutes by integer variable ‘duration’.
• To achieve that we have implemented one constructor function which
accepts one argument of type integer as follow:
Here, we have created an object “t1” of class “Time” and during the creation
we have assigned integer variable “duration”. It will pass time duration to the
constructor function and assign to the “hrs” and “min” members of the class
“Time”.
We have to note that during type conversion using the constructor we can
pass only one argument and we can do type conversion at the type of
initialization only.
106
Using Operator Overloading:-
• We can also achieve type conversion by operator overloading.
• We can overload assignment operator for this purpose.
• Above example of Time class can be rewritten for type conversion using
operator overloading concept to overload the assignment operator (=) as
follow:
/* Program to convert from basic type to class type using operator overloading*/
#include
"iostream.h"
#include "conio.h"
class Time
{
int hrs,min; public:
void display();
void operator=(int); // overloading function
};
void Time::display()
{
cout<<hrs<< ": Hour(s) "<<endl ;
cout<<min<<": Minutes"<<endl ;
}
void Time::operator=(int t)
{
cout<<"Basic Type to ==> Class Type Conversion..."<<endl; hrs=t/60;
min=t%60;
}
void main()
\
{
clrscr(); Time t1;
int duration;
cout<<"Enter time duration in minutes"; cin>>duration;
cout<<"object t1 overloaded assignment..."<<endl; t1=duration;
t1.display();
cout<<"object t1 assignment operator 2nd method..."<<endl;
t1.operator=(duration);
t1.display();
getch();
}
107
Conversion from class type to basic type:-
The constructor functions do not support conversion from a class to basic
type. C++ allows us to define a overload casting operator that convert a class
type data to basic type.
The general syntax of an overloaded casting operator function, also referred
to as a conversion function, is :
In the below example, operator double () converts a class object to type
double.
operator typename()
{
// Program statement
}
Example :
108
Example :
Explanation :-
obj1 is an object of class one and obj2 is an object of class two. The class two
type data is converted value is assigned to the obj1. Since the conversion
takes place from class two to class one, two is known as the source and one
is known as the destination class.
109
The following program uses classes and shows how to convert data of
one type to another
#include <iostream>
using namespace std;
class stock2 ;
class stock1
{
int code , item ;
float price ; public :
stock1 ( int a , int b , int c )
{
code = a ; item
= b ; price = c ;
};
void disp ()
{
cout << " code " << code << " \n " ; cout
<< " items " << item << " \n " ;
cout << " price per item Rs. " << price << " \n " ;
};
int getcode ()
{ return code; }; int
getitem ()
{ return item ; }; int
getprice ()
{ return price ; };
operator float ()
{
return ( item*price ) ;
};
};
class stock2
{
int code ;
float val ;
110
public : stock2 ()
{
code = 0; val = 0 ;
};
stock2( int x , float y )
{
code = x ; val = y ;
};
void disp ()
{
cout << " code " << code << " \n " ;
cout << " total value Rs. " << val << " \n " ;
};
stock2( stock1 p )
{
code = p.getcode() ;
val = p.getitem() * p.getprice() ;
};
};
int main()
{
stock1 i1 ( 101 , 10 ,125.0 ) ;
stock2 i2 ;
float tot_val = i1; i2 = i1 ;
cout << " Stock Details : Stock 1 type " << " \n " ; i1.disp ();
cout << " Stock Value " << " - " ; cout << tot_val << " \n " ;
cout << " Stock Details : Stock 2 type " << " \n " ; i2.disp () ;
return 0 ;
}
111
UNIT - 7
112
INHERITANCE
In object-oriented programming , inheritance is the mechanism of basing
an object or class upon another object (prototype based inheritance) or class
(class-based inheritance), retaining similar implementation.
Also defined as deriving new classes (sub classes) from existing ones such
as super class or base class and then forming them into a hierarchy of
classes.
Inheritance allows programmers to create classes that are built upon existing
classes, to specify a new implementation while maintaining the same
behaviors (realizing an interface), to reuse code and to independently
extend original software via public classes and interfaces.
Inheritance was invented in 1969 for Simula and is now used throughout
many object-oriented programming languages such as Java, C++ or
Python.
The term "inheritance" is loosely used for both class-based and prototype-
based programming, but in narrow use the term is reserved for class-based
programming (one class inherits from another), with the corresponding
technique in prototype-based programming being instead called delegation
(one object delegates to another).
113
To distinguish these concepts, subtyping is also known as interface
inheritance, whereas inheritance as defined here is known asimplementation
inheritance or code inheritance.
TYPES OF INHERITANCE:-
There are various types of inheritance, based on paradigm and specific
language.
SINGLE INHERITANCE
In single inheritance, a class is allowed to inherit from only one class. i.e.
one sub class is inherited by one base class only
114
MULTIPLE INHERITANCE
where one class can have more than one superclass and inherit features
from all parent classes.
MULTILEVEL INHERITANCE
where a subclass is inherited from another subclass. It is not uncommon that
a class is derived from another derived class as shown in the figure ".
The class A serves as a base class for the derived class B, which in turn
serves as a base class for the derived class C.
115
HIERARCHICAL INHERITANCE
This is where one class serves as a superclass (base class) for more than
one sub class. For example, a parent class, A, can have two subclasses B
and C. Both B and C's parent class is A, but B and C are two separate
subclasses.
HYBRID INHERITANCE
Hybrid inheritance is when a mix of two or more of the above types of
inheritance occurs. An example of this is when class A has a subclass B
which has two subclasses, C and D. This is a mixture of both multilevel
inheritance and hierarchal inheritance.
116
NEED OF PROTECTED MEMBERS:-
The private members of a class cannot be directly accessed outside the
class. Only methods of that class can access the private members directly.
117
For example, let's imagine a series of classes to describe two kinds of
shapes: rectangles and triangles.
These two shapes have certain common properties height and a width (or
base).
This could be represented in the world of classes with a class Shapes from
which we would derive the two other ones :
/**
* A class Shape that holds width and height
* of any shape
*/
publicclassShape
{
protecteddouble height; // To hold height.
protecteddouble width; //To hold width or base
/**
* The setValue method sets the data
* in the height and width field.
*/
publicvoidsetValues(double height, double width)
{
this.height = height;
this.width = width;
}
}
118
Program : (Rectangle )
/**
* This class Rectangle calculates
* the area of rectangle
*/
publicclassRectangleextendsShape
{
/**
Program : (Triangle)
/**
* This class Triangle calculates
* the area of triangle
*/
publicclassTriangleextendsShape
{
/**
* The method returns the area
* of triangle.
*/
publicdoublegetArea()
{
return height * width / 2; //accessing protected members
}
119
Program : (TestProgram)
/**
* This program demonstrates the Rectangle and
* Triangle class, which inherits from the Shape class.
*/
publicclassTestProgram
{
publicstaticvoidmain(String[] args)
{
//Create object of Rectangle.
Rectangle rectangle = new Rectangle();
Output :
120
Area of rectangle : 20.0
APPLICATION OF INHERITANCE:-
OVERRIDING
121
The answer varies between programming languages, and some languages
provide the ability to indicate that a particular behavior is not to be
overridden and should behave as defined by the base class.
For instance, in C#, the base method or property can only be overridden in a
subclass if it is marked with the virtual, abstract, or override modifier, while in
programming languages such as Java, different methods can be called to
override other methods
CODE REUSE
By default the subclass retains all of the operations of the base class, but
the subclass may override some or all operations, replacing the base-class
implementation with its own.
The base class comprises operations to compute the sum of the squares
between two integers.
The subclass re-uses all of the functionality of the base class with the
exception of the operation that transforms a number into its square,
replacing it with an operation that transforms a number into its square and
cube respectively.
122
In most quarters, class inheritance for the sole purpose of code reuse has
fallen out of favor.
that is, they implement the same methods. The parent class can be a
combination of implemented operations and operations that are to be
implemented in the child classes.
Often, there is no interface change between the supertype and subtype- the
child implements the behavior described instead of its parent class.
123
UNIT- 8
124
MANAGING CONSOLE I\O OPERATIONS
The standard C++ library is iostream and standard input / output functions in
C++ are:
1. cin
2. cout
These functions are available in header file <iomanip>. iomanip refers input
output manipulations.
A) width(n)
Syntax:
cout<<setw(int n )
125
Example:
#include<iostream>
#include<iomanip>
int x=10;
cout<<setw(20)<<variable;
return 0;
Output
10
B) fill(char)
Syntax:
cout<<setfill('character')<<variable;
126
Example:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
Output
##################10
D) Precision (n)
Syntax:
cout<<setprecision('int n')<<variable;
127
Example:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
return 0;
}
Output:-
10.123
E) setflag(arg 1, arg,2)
This function is used for setting format flags for output.
Syntax:
setiosflags(argument 1, argument 2);
F) unsetflag(arg 2)
This function is used to reset set flags for output.
Syntax:
resetiosflags(argument 2);
G) setbase(arg)
This function is used to set basefield of the flag.
Syntax:
setbase(argument);
128
Unformatted console input output operations:-
These input / output operations are in unformatted mode. The following are
operations of unformatted console input / output operations:
A) void get()
It is a method of cin object used to input a single character from keyboard. But
its main property is that it allows wide spaces and newline character.
Syntax:
char c=cin.get();
Example:
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}
Output
129
B) void put()
Syntax:
cout.put(variable / character);
Example:
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
return 0;
}
Output
130
C) getline(char *buffer,int size)
This is a method of cin object and it is used to input a string with multiple
spaces.
Syntax:
char x[30];
cin.getline(x,30);
Example:
include<iostream>
int main()
cout<<"Enter name:";
char c[10];
cout<<c<<endl;
return 0;
Output
Enter name :Divyanshu
Divyanshu
131
Input / output streams:-
In the Java API, an object from which we can read a sequence of bytes is
called an input stream. An object to which we can write a sequence of bytes
is called an output stream.
These sources and destinations of byte sequences can be—and often are—
files, but they can also be network connections and even blocks of memory.
The abstract classes InputStream and OutputStream are the basis for a
hierarchy of input/output (I/O) classes.
NOTE :
These input/output streams are unrelated to the streams that you saw in the
preceding chapter. For clarity, we will use the terms input stream,
output stream, or input/output stream whenever we discuss streams that
are used for input and output.
In Java, streams are the sequence of data that are read from the source
and written to the destination.
An input stream is used to read data from the source. And, an output
stream is used to write data to the destination.
132
class HelloWorld {
System.out.println("Hello, World!");
For example, in our first Hello World example, we have used System.out to
print a string. Here, the System.out is a type of output stream.
Similarly, there are input streams to take input.
133
Types of Streams
● Byte Stream
● Character Stream
Byte Stream
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called
InputStream and OutputStream.
Character Stream
All the character stream classes are derived from base abstract classes
Reader and Writer.
134
UNIT-9
135
Files operation
In C++, files are mainly dealt by using three classes fstream, ifstream,
ofstream available in fstream headerfile.
136
In C++, you open a file, you must first obtain a stream. There
are the following three types of streams:
input
output
input/output
ifstream fin;
ofstream fout
fstream fio;
137
Opening a File in C++:-
Once a stream has been created, next step is to associate a file with it. And
thereafter the file is available (opened) for processing.
The first method is preferred when a single file is used with a stream.
However, for managing multiple files with the same stream, the second
method is preferred. Let's discuss each of these methods one by one.
To open a file named myfile as an input file (i.e., data will be need from it
and no other operation like writing or modifying would take place on the file),
we shall create a file stream object of input type i.e., ifstream type. Here is
an example:
The above given statement creates an object, fin, of input file stream. The
object name is a user-defined name (i.e., any valid identifier name can be
given). After creating the ifstream object fin, the file myfile is opened and
attached to the input stream, fin. Now, both the data being read from myfile
has been channelised through the input stream object.
138
Now to read from this file, this stream object will be used using the getfrom
operator (">>"). Here is an example:
char ch;
fin >> ch ; // read a character from the
file >> amt ; // a floating-point number form the file
Similarly, when you want a program to write a file i.e., to open an output file
(on which no operation can take place except writing only). This will be
accomplish by
Now, to write something to it, you can use << (put to operator) in
familiar way. Here is an example,
The connections with a file are closed automatically when the input and the
output stream objects expires i.e., when they go out of scope.
(For example, a global object expires when the program terminates). Also,
you can close a connection with a file explicitly by using the close() method :
You can reconnect the stream to the same file or to another file, if required.
Closing a file flushes the buffer which means the data remaining in the
buffer (input or output stream) is moved out of it in the direction it is ought to
be.
For example, when an input file's connection is closed, the data is moved
from the input buffer to the program and when an output file's connection is
closed, the data is moved from the output buffer to the disk file.
If the situation requires simultaneous processing of two files, then you need
to create a separate stream for each file.
To use this approach, declare a stream object without initializing it, then use
a second statement to associate the stream with a file. For example,
140
ifstream fin; // create an
input stream
fin.open("Master.dat", ios::in); // associate fin
stream with file Master.dat
: // process
Master.dat
fin.close();
// terminate association
with Master.dat
fin.open("Tran.dat", ios::in); // associate fin
stream with file Tran.dat
:
// process
Tran.dat
fin.close(); // terminate
association
The above code lets you handle reading two files in succession. Note that
the first file is closed before opening the second one.
The filemode describes how a file is to be used : to read from it, to write to it,
to append it, and so on.
When you associate a stream with a file, either by initializing a file stream
object with a file name or by using the open() method, you can provide a
second argument specifying the file mode, as mentioned below :
stream_object.open("filename", (filemode) ) ;
The second method argument of open(), the filemode, is of type int, and you
can choose one from several constants defined in the ios class.
141
List of File Modes in C++
Following table lists the filemodes available in C++ with their meaning:-
142
If the ifstream and ofstream constructors and the open() methods take two
arguments each, how have we got by using just one in the previous
examples ? As you probably have guessed, the prototypes for these class
member functions provide default values for the second argument (the
filemode argument). For example, the ifstream open() method and
constructor use ios :: in (open for reading) as the default value for the mode
argument, while the ofstream open() method and constructor use ios :: out
(open for writing) as the default.
The fstream class does not provide a mode by default and, therefore, one
must specify the mode explicitly when using an object of fstream class.
Both ios::ate and ios::app place you at the end of the file just opened. The
difference between the two is that the ios::app mode allows you to add data
to the end of the file only, when the ios::ate mode lets you write data
anywhere in the file, even over old data.
You can combine two or more filemode constants using the C++ bitwise OR
operator (symbol |). For example, the following statement :
ofstream fout;
fout.open("Master", ios :: app | ios :: nocreate);
will open a file in the append mode if the file exists and will abandon the file
opening operation if the file does not exist.
To open a binary file, you need to specify ios :: binary along with the file
mode, e.g.,
fout.open("Master", ios :: app | ios :: binary);
or,
fout.open("Main", ios :: out | ios :: nocreate | ios
:: binary);
143
Closing a File in C++:-
As already mentioned, a file is closed by disconnecting it with the
stream it is associated with. The close() function accomplishes this
task and it takes the following general form :
stream_object.close();
For example, if a file Master is connected with an ofstream object fout, its
connections with the stream fout can be terminated by the following
statement :
fout.close() ;
144
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
ofstream fout;
ifstream fin;
char fname[20];
char rec[80],
ch;
clrscr();cout<<"Enter file name: ";
cin.get(fname, 20); fout.open(fname, ios::out);
if(!fout)
{
cout<<"Error in opening the file "<<fname; getch();
exit(1);
}
cin.get(ch);
cout<<"\nEnter a line to store in the file:\n"; cin.get(rec, 80);
fout<<rec<<"\n";
cout<<"\nThe entered line stored in the filesuccessfully..!!";
cout<<"\nPress any key to see...\n"; getch();
fout.close();
fin.open(fname, ios::in); if(!fin)
{
cout<<"Error in opening the file "<<fname; cout<<"\nPress
any key to exit..."; getch();
exit(2);
}
cin.get(ch);
fin.get(rec, 80);
cout<<"\nThe file contains:\n";
cout<<rec;
cout<<"\n\nPress any key to exit...\n"; fin.close();
getch();
}
145
Programming with a files:-
Below is the implementation by using ifstream &
ofstream classes.
Ifstream:- The ifstream is a file stream class used for file
handling. To use ifstream header file fstream is used. It is used
for reading input from the file. In order to read from a file an object
of type ifstream is created.
Use as ifstream:- Reading a text file is very easy using
an ifstream (input file stream).
1. Include the necessary headers. #include <fstream> using namespace
std;
2. Declare an input file stream ( ifstream ) variable. ...
3. Open the file stream. ...
4. Check that the file was opened. ...
5. Read from the stream in the same way as cin . ...
6. Close the input stream
/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*/
#include <iostream>
/* fstream header file for ifstream, ofstream, fstream classes */
#include <fstream> using
namespacestd;
// Driver Code
int main()
{
// Creation of ofstream class object ofstream fout;
string line;
// by default ios::out mode, automatically deletes
// the content of file. To append the content, open in ios:app
146
// fout.open("sample.txt", ios::app) fout.open("sample.txt");
// Execute a loop If file successfully opened while (fout) {
// Read a Line from standard input getline(cin, line);
// Press -1 to exit if (line == "-1")
break;
// Write line in file fout << line << endl;
}
// Close the File
fout.close();
// Creation of ifstream class object to read the file
ifstream fin;
// by default open mode = ios::in mode fin.open("sample.txt");
// Execute a loop until EOF (End of File) while (fin) {
// Read a Line from File
getline(fin, line); // Print line in Console cout << line << endl;
} // Close the file
fin.close();
return 0;
}
1 Ofstream
This data type represents the output file stream and is used to
create files and to write information to files.
2 Ifstream
This data type represents the input file stream and is used to read
information from files.
3 Fstream
This data type represents the file stream generally, and has the
capabilities of both ofstream and ifstream which means it can
create files, write information to files, and read information from
files.
Difference between using ifstream and ofstream with cin and cout. ...
It says that ifstream is used to read data from a file, while ofstream is used
to write data.
Examples:-
fstream
/* File Handling with C++ using fstream class object*/
/* To write the Content in File */
/* Then to read the content of file*/
#include <iostream>
/* fstream header file for ifstream, ofstream,
fstreamclasses */
#include
<fstream>
using
namespace
std;
// Driver Code
int main()
{
// Creation of fstream class object fstream
fio;
string line;
// by default openmode = ios::in|ios::out mode
148
// Automatically overwrites the content of file, to
append
// the content, open in ios:app
// fio.open("sample.txt",
ios::in|ios::out|ios::app)
// ios::trunc mode delete all conetent
before open
fio.open("sample.txt", ios::trunc | ios::out |
ios::in);
// Execute a loop If file successfully Opened while (fio) {
// Read a Line from standard input getline(cin, line);
// Press -1 to exit if (line == "-1")
break;
// Write line in file fio << line << endl;
}
// Execute a loop untill EOF (End of File)
// point read pointer at beginning of file
fio.seekg(0, ios::beg); while (fio) {
// Read a Line from File
getline(fio, line);
// Print line in Console cout
<< line << endl;
}
// Close the file fio.close();
return 0;
}
149
UNIT-10
150
Virtural & friend function
Pointers to objects
This pointers
Virtual function
Pure virtual function
Concept of late & early binding
Pointer to objects:-
A Variable That Holds an Address value is called a Pointer variable or
simply pointer. We already discussed about pointer that's point to Simple
data types likes int, char, float etc. So similar to these type of data type,
Objects can also have an address, so there is also a pointer that can
point to the address of an Object, This Pointer is Known as This Pointer.
This pointer:-
Every Object in C++ has access to its own address through an important
pointer called This Pointer. The This Pointer is an implicit parameter to all
member functions. Therefore, inside a member function, this may be
used to refer to the invoking object. Whenever a member function is
called, it is automatically passed an implicit arguments that is This pointer
to the invoking object (i.e. The object on which the function is invoked).
151
Let's have an simple example of This pointer.
public:
voidsetx(int a) //simple function.
{
this->x=a;
}
};
main()
{
Point obj1; //1st Object of Class Point.
Point obj2; //2nd Object of Class point.
obj1.setx(10); //function calling using 1st object.
obj2.setx(30); //function calling using 2nd object.
return 0;
}
In Above Example, there is an simple class having two objects, and a
simple function that take an integer as an parameter, and initialize it to
variable x. Now in above Example, Might be you have a Question, That
So the Answer is, When the function is called the address of the calling
object is passed implicitly. so in order to understand, consider the
following statement.
obj1.setx( 10 );
Here value 10 is passed explicitly to the function setx() but at the same
time Address of obj1 is passed implicitly to the function. " Int a" holds the
value 10, and the address of obj1 stored in a pointer named " this " pointer.
Similarly when obj2 calls the function of the class, " This " pointer holds
address of obj2 to refer obj2's data member. at shown in figure:
152
C++ DECLARATION AND USES OF OBJECT POINTERS:
Just like Other Pointers, the object pointers are declared by placing in
front of a object pointer's name. The Syntax is:
class_name*Object_pointer_name;
In above Syntax, class_Name is the name of an already defined class and
object_pointer_name is the pointer to an object of this class type. For
example: To declared an Pointer ptr an an object pointer of class Date, We
shall write:
Date *ptr;
In Above syntax, Date is already defined class. When accessing members
of a class using an object pointer, the Error Operator -> is used instead of
Dot Operator. Let's take an simple example, This Example illustrates how
to access an object given a pointer to it.
153
154
155
Virtual function:-
A Virtual Function is a function that is declared as Virtual in a base class
and redefined in one or more derived classes. Thus, each derived class
can have its own version of a Virtual Function.
If there are Member functions with same name in base class and derived
class, Virtual Functions gives Programmer Capability to call member
function of different class by a same function call depending upon different
context. This feature in C++ Programming is known as Polymorphism
which is one of the important feature of Object Oriented Programming. If a
base Class and derived Class has same function and if we write code to
access that function using pointer of base class then, The function in the
base class is executed even, if the object of derived class is referenced
with that pointer variable. This can be demonstrated by this Example:
/* Virtual Function Concept: InfoBrother:*/
#include<iostream>
using namespace std;
class Base //Base Class:
{
public:
void display() //Simple function to display some content.
{
cout<<" Base Class "<<endl;
}
};
class Derived: public Base //Derived class. Using Inheritance concept.
{
public:
void display() //redefine Same function.
{
cout<<" Derived Class "<<endl;
}
};
main()
{
Base *ptr; //pointer object of type Base.
Derived obj; //object of type Derived
ptr->display(); //function calling using Base-Class object:
ptr=&obj; //pointer point to Address of Derived Class.
156
ptr->display(); //function calling using pointer, that point to Derived
class.
return 0;
}
Check Output
In Above Example, even if the object of derived class Derived is put in
pointer to Base Class, display() of the base class is executed. so in order
to Execute the member function of Derived Class, we Need to
use Virtual Keyword in the base class along with display() Function,
which makes that function existing in appearance only but, we can't call
that function. So let's try same example using Virtual Keyword.
/* Virtual Function: InfoBrother:*/
#include<iostream>
using namespace std;
class Base //Base Class:
{
public:
virtual void display() //Virtual Function.
{
cout<<" Base Class "<<endl;
}
};
class Derived: public Base //Derived class. Using Inheritance concept.
{
public:
void display() //redefine same Function.
{
cout<<" Derived Class "<<endl;
}
};
main()
{
Base *ptr; //pointer object of type Base.
Derived obj; //object of type Derived
ptr->display(); //function calling using Base-Class object:
ptr=&obj; //pointer point to Address of Derived Class.
ptr->display(); //function calling using pointer, that point to Derived class.
return 0;
}
157
After the function of Base is made Virtual, code ptr->display() will call the
display() of the derived class depending upon the content of pointer. in this
example, display() function of two different classes are called with same
code which is one of the example of Runtime Polymorphism in C++
Programming using Virtual function.
Adding =0 to virtual function does not assign value, it simply indicates the
virtual function is a pure function.
/*Abstract Class. (because of Pure virtual function)*/
class Base
{
public:
void display(); //Not virtual function:
virtual void display(); //virtual function but Not Pure:
virtual void display()=0; //Pure Virtual function:
};
158
Here, Base is an Abstract class, because it has a pure Virtual function, so
no objects of class Base can be directly created. Base is explicitly mean
to be a base class. Let's have an complete example for Pure Virtual
Function.
#include <iostream>
using namespace std;
public:
voidget_data() /*this function is not virtual. */
{
cin>>l;
}
virtual float area() = 0; /* Pure virtual function */
};
class Square : public Shape //derived class.
{
public:
float area()
{
return l*l;
}
};
class Circle : public Shape //derived class.
{
public:
float area()
{
return 3.14*l*l;
}
};
int main()
{
159
Square squ; //object of type Square:
Circle cir; //Object of type Circle:
cout<<"Enter length to calculate area of a square: ";
squ.get_data();
cout<<"Area of square: "<<squ.area();
cout<<"\n\nEnter radius to calculate area of a circle:";
cir.get_data();
cout<<"Area of circle: "<<cir.area();
return 0;
160
// CPP Program to illustrate early binding.
// Any normal function call (without virtual)
// is binded early. Here we have taken base
// and derived class example so that readers
// can easily compare and see difference in
// outputs.
#include<iostream>
usingnamespacestd;
classBase
{
public:
voidshow() { cout<<" In Base \n"; }
};
classDerived: publicBase
{
public:
voidshow() { cout<<"In Derived \n"; }
};
intmain(void)
{
Base *bp = newDerived;
161
Late Binding : (Run time polymorphism) In this, the compiler adds code
that identifies the kind of object at runtime then matches the call with the
right function definition (Refer this for details). This can be achieved by
declaring a virtual function.
162