0% found this document useful (0 votes)
11 views88 pages

C - 16 Mark

This document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including key principles such as classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing. It also outlines the structure of a C++ program, detailing the components like include files, class declarations, member functions, and the main function. Additionally, it introduces C++ tokens, including keywords, identifiers, constants, and their respective rules and classifications.

Uploaded by

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

C - 16 Mark

This document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including key principles such as classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing. It also outlines the structure of a C++ program, detailing the components like include files, class declarations, member functions, and the main function. Additionally, it introduces C++ tokens, including keywords, identifiers, constants, and their respective rules and classifications.

Uploaded by

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

UNIT 1

1. Basic Concepts of OOPs in C++


TABLE OF CONTENT:
1. Introduction
2. Class
3. Objects
4. Encapsulation
5. Abstraction
6. Polymorphism
7. Inheritance
8. Dynamic Binding
9. Message Passing

Object-oriented programming – As the name suggests uses objects in


programming. Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism, etc in programming.
The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
Characteristics of an Object Oriented Programming language

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.

● 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.
We can say that a Class in C++ is a blue-print representing a group of objects which
shares some common properties and behaviors.

Object:
An Object is an identifiable entity with some characteristics and behaviour. An
Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
class person
{
char name[20];
int id;
public:
void getdetails(){}
};

int main()
{
person p1; // p1 is a object
}

Object take up space in memory and have an associated address like a record in pascal or
structure or union in C.
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:
In normal terms, 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.
Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides
the data. In the above example, the data of any of the section like sales, finance or
accounts are hidden from any other section.

Abstraction:
Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.

● Abstraction using Classes: We can implement Abstraction in C++ using classes.


The class helps us to group data members and member functions using available
access specifiers. A Class can decide which data member will be visible to the
outside world and which is not.
● Abstraction in Header files: One more type of abstraction in C++ can be header
files. For example, consider the pow() method present in math.h header file.
Whenever we need to calculate the power of a number, we simply call the function
pow() present in the math.h header file and pass the numbers as arguments without
knowing the underlying algorithm according to which the function is actually
calculating the power of numbers.

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 behaviour 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.
● Function Overloading: Function overloading is using a single function name to
perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, sometimes there are
2 integers; sometimes there are 3 integers. We can write the Addition Method with the
same name having different parameters; the concerned method will be called according to
parameters.

Inheritance:
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
● 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.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

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.

Message Passing:
Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired results.
Message passing involves specifying the name of the object, the name of the function and
the information to be sent.

2.Structure of C++ program


Include Files
1. Documentation Section
2. Preprocessor Directives or Compiler Directives Section
(i) Link Section
(ii) Definition Section
3. Global Declaration Section
Class declaration or definition
1. Class name or name of class
2. Data Members
3. Member Functions
4. Access Specifiers
Member function definition
1. Defining function inside class declaration
2. Defining function outside class declaration
Main C++ program function called main ( )
1. Beginning of the program: Left brace {
(i) Object declaration part;
(ii) Accessing member functions (using dot operator);
2. End of the main program: Right brace}

Include files

1. Documentation Section
In Documentation section we give the Heading and Comments. Comment
statement is the non-executable statement. Comment can be given in two ways:
(i) Single Line Comment: Comment can be given in single line by using "II".
The general syntax is: II Single Text line
(ii) Multiple Line Comment: Comment can be given in multiple lines starting by
using "/*" and end with "*/".
2. Preprocessor Directives
Pre-compiler statements are divided into two parts.
(i) Link Section:
In the Link Section, we can link the compiler function like cout<<, cin>>,
sqrt ( ), fmod ( ), sleep ( ), clrscr ( ), exitO, strcatO etc.
ii) Definition Section:
The second section is the Definition section by using which we can define a
variable with its value. For this purpose define statement is used.
3. Global Declaration Section
Declare some variables before starting of the main program or outside
the main program. These variables are globally declared and used by the main
function or sub function
Class declaration or definition

A class is an organization of data and functions which operate on them. Data types are
called data members and the functions are called member functions. The combination of
data members and member functions constitute a data object or simply an object.

The general syntax or general form of the class declaration is as follows:

class <name of class>


{
private:
data members;
member functions O;
public:
data members;
member functions O;
protected:
data members;
member functions O;
};
mainO
{
<name of class> obj1;
obj1.member function O;
obj1.member functionO;
getchO;
}

1. Class name or name of class


It is mainly the name given to a particular class. It serves as a name specifier for
the class, using which we can create objects. The class is specified by keyword
"class".
For example: class Circle
Here Circle is the class name.
2. Data Members
These are the data-type properties that describe the characteristics of a class. We
can declare any number of data members of any type in a class. We can say that the
variables in C and data members in C++.
For example: float area;
3. Member Functions
These are the various operations that can be performed to data members of that
class..
For example: void read(); void display();
4. Access Specifiers
Access Specifiers are used to identify access rights for the data members and
member functions of the class.
There are three main types of access Specifiers in C++ programming language:
1. Private: A private member within a class denotes that only members of the
same class have accessibility. The private member is not accessible
from outside the class.
2. Public: Public members are accessible from outside the class.
3. Protected: A protected access specifier is a stage between private and public
access. If member functions defined in a class are protected, they
cannot be accessed from outside the class but can be accessed from
the derived class (inheritance).

Member function definition

1. Defining member function inside of the class definition (member function


definition with declaration)
Consider the following syntax
class class_name
{
private:
data_type variable_names;
public:
return_type function_name(parameter_list)
{
function_body;
}
};
Example : Definition of a member function inside a class
class book
{
char title[30];
float price;
public:
void getdata(char [],float); II declaration
void putdata()//definition inside the class
{
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
};

2. Defining member function outside of the class definition


Defining a member function outside a class requires the function declaration
(function prototype) to be provided inside the class definition.
The definition of member function outside the class differs from normal function
definition, as the function name in the function header is preceded by the class name
and the scope resolution operator (: :).
The scope resolution operator informs the compiler what class the member
belongs to.
class class_name
{
private:
data_type variable_names;
public:
return_type function_name(parameter_list);
};
The syntax for defining a member function outside the class is

Return_type class_name :: function_name (parameter_list)


{
// body of the member function
}

Main C++ program function called main ( )

main function is where a program starts execution. Main () program is the C++
program's main structure in which we process some statements. The main function
usually organizes at a high level the functionality of the rest of the program.
The general syntax is: main ( )
1. Beginning of the Main Program: Left Brace {
(The beginning of the main program can be done by using left curly brace "{").
(i) Object declaration part
We can declare objects of class inside the main program or outside the main
program.
For example: b1 is the object of the class book. We can create any number of
objects of a given class.

(ii) Accessing member functions (using dot operator)


The member function define in the class are access by using dot (.)
operator. Suppose we have two member functions void getdata() and void
putdata(). We have to access these member functions in the main program.
syntax:
Obj1. Member function ();
For example:
b1.getdata (“balagurusamy”,300);
Here b1 is object and getdata() is the member function of class book.
2. Ending of The Main Program: Right Brace}
(The right curly brace "}" is used to end the main program).
main ( )
{
book b1;
b1.getdata(“balagurusamy”,300);
b1.putdataO;
getch( );
}

3. Object-Oriented Programming Paradigm

● The major motivating factor in the invention of object-oriented approch is to


remove some of the flaws encountered in the procedural approch.
● OOP treats data as a critical element in the program development and does not
allow it to flow freely around the systems.
● It ties data more closely to the functions that operate on it, and protects it from
accidental modification from outside functions.
● OOP allows decomposition of a problem into a number of entities called objects
and then builds data and functions around these objects.
● The data of an object can be accessed only by the function associated with that
object.
● However, functions of one object can access the the functions of other objects.

Features of object-oriented programming are

● Emphasis is on data rather than procedure.


● Programs are divided into what are known as objects.
● Data structures are designed such that they characterize the objects.
● Data is hidden and cannot be accessed by external functions.
● Objects may communicate with each other through functions.
● New data and functions can be easily added whenever necessary.
● Follows bottom-up approach in program design.

UNIT -2
C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. Keyword:
Keywords are those words whose meaning is already defined by Compiler.
These keywords cannot be used as an identifier. Note that keywords are the collection
of reserved words and predefined identifiers..Every Keyword exists in lower case

C language supports 32 keywords which are given below:


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

While in C++ there are 31 additional keywords other than C Keywords they
are:
asm bool catch class
const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t

2. Identifiers:
Identifiers are used as the general terminology for naming of variables,
functions and arrays. These are user defined names consisting of arbitrarily
long sequence of letters and digits with either a letter or the underscore(_) as a
first character. Identifier names must differ in spelling and case from any
keywords. You cannot use keywords as identifiers; they are reserved for
special use.

There are certain rules that should be followed while naming c


identifiers:
● They must begin with a letter or underscore(_).
● They must consist of only letters, digits, or underscore. No other special
character is allowed.
● It should not be a keyword.
● It must not contain white space.
● It should be up to 31 characters long as only first 31 characters are
significant.
Some examples of c identifiers:

NAME REMARK

_A9 Valid
Invalid as it contains special character other than the
Temp.var underscore
void Invalid as it is a keyword

1. Constants:
Constants are also like normal variables. But, only difference is, their values
can not be modified by the program once they are defined. Constants refer to
fixed values. They are also called as literals.

Constants may belong to any of the data type.Syntax:


const data_type variable_name; (or) const data_type *variable_name;

Types of Constants:
● Integer constants – Example: 0, 1, 1218, 12482
● Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
● Octal & Hexadecimal constants – Example: octal: (013 )8 =
(11)10, Hexadecimal: (013)16 = (19)10
● Character constants -Example: ‘a’, ‘A’, ‘z’
● String constants -Example: “GeeksforGeeks”

2. Strings:
Strings are nothing but an array of characters ended with a null character
(‘\0’).This null character indicates the end of the string. Strings are always
enclosed in double quotes. Whereas, a character is enclosed in single quotes in C
and C++.

Declarations for String:


● char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’,
‘\0’};
● char string[20] = “geeksforgeeks”;
● char string [] = “geeksforgeeks”;

1. Special Symbols:
The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose.[] () {}, ; * = #
● Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
● Parentheses(): These special symbols are used to indicate function calls
and function parameters.
● Braces{}: These opening and ending curly braces marks the start and end
of a block of code containing more than one executable statement.
● comma (, ): It is used to separate more than one statements like for
separating parameters in function calls.
● semi colon : It is an operator that essentially invokes something called an
initialization list.
● asterick (*): It is used to create pointer variable.
● assignment operator: It is used to assign values.
● pre processor(#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.

2. Operators:
Operators are symbols that triggers an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators
can be classified as follows:
● Unary Operators: Those operators that require only single operand to act
upon are known as unary operators.For Example increment and decrement
operators
● Binary Operators: Those operators that require two operands to act upon
are called binary operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
Ternary Operators: These operators requires three operands to act upon.
For Example Conditional operator(?:).
For more information about operators
2. Control Structure in C++
A control structure is a block of programming that analyzes variables
and chooses a direction in which to go based on given parameters. The term
flow control details the direction the program takes

Types of Control Structure

1.Branching
2.Looping

Branching statement

⮚ if statement
⮚ if..else statements
⮚ if-else-if ladder
⮚ nested if statements
⮚ switch statements

If Statement:

The if statement selects and executes the statement(s) based on a given


condition. If the condition evaluates to True then a given set of statement(s) is
executed.
If the condition evaluates to False, then the given set of statements is
skipped and the program control passes to the statement following the if statement.

Syntax
if (condition)
{
statement 1;
statement 2;
statement 3;
}
Example
if (mark>40)
{
Cout<<”PASS”;
}
If-else Statement:

The if-else statement comprises two parts, namely, if and else.


The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false he else statement ll be execute . We can use
the else statement with if statement to execute a block of code when the condition
is false

Syntax
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
if(x>y)
cout<<”X is greater”;
else
cout<<”y is greater”;

Nested if-else Statement:

A nested if-else statement contains one or more if-else statements. Nested if


statements means an if statement inside another if statement.
Syntax
if (condition1)
{
// Executes when
condition1 is true
if (condition2)
{
// Executes when
condition2 is true
}
Else{}
}
Example
if (a>b)
{
if (a>c)
cout<<”a is largest”;
}
else //nested if-else
statement within else
{
if (b>c)
cout<<”b is largest”;
else
cout<<”c is largest”;
}

if-else-if ladder

The if-else-if staircase, has an if-else statement within the outermost else
statement. The inner else statement can further have other if-else statements. As
soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed
Syntax
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example
char ch;
cout<<"Enter an alphabet:";
cin>>ch;
if( (ch>='A') && (ch<='Z'))
cout <<"The alphabet is in upper
case";
else if ( (ch>=' a') && (ch<=' z' ) )
cout<<"The alphabet is in lower
case";
else
cout<<"It is not an alphabet";
return 0;
}

The switch Statement:


The switch statement selects a set of statements from the available sets of
statements. The switch statement tests the value of an expression in a sequence and
compares it with the list of integers or character constants.
Syntax
switch(expression)
{
case <constant1>: statement1;
[break;]
case <constant2>: statement2;
[break;]
case <constant3>: statement3;
[default: statement4;]
[break;]
}
Statement5;
Example
cin>>x;
int x;
switch(x)
{
case l: cout<<"Option1 is
selected";
break;
case 2: cout<<"Option2 is
selected";
break;
case 3: cout<<"Option3 is
selected";
break;
case 4: cout<<"Option4 is selected;
break;
default: cout<<"Invalid option!";
}
Looping

A loop statement allows us to execute a statement or group of statements


multiple times and following is the general from of a loop statement in most of the
programming languages
C++ while and do...while Loop. Loops are used in programming to repeat a
specific block of code. ... In computer programming, loop repeats a certain block
of code until some end condition is met.
Types of Loop
1.Entry control Loop
i)For Loop
ii)While Loop
2.Exit Control Loop
i) Do while Loop

for Loop

1. The initialization statement is executed only once at the beginning.


2. Then, the test expression is evaluated.
3. If the test expression is false, for loop is terminated. But if the test
expression is true, codes inside body of for loop is executed and update
expression is updated.
4. Again, the test expression is evaluated and this process repeats until the test
expression is false.
Syntax

for(initializationStatement;
testExpression;increment/decrement
)

// codes

}
Example

for(i=0;i<=5;i++)

Cout<<” SRM IST”


}

while Loop

● The while loop evaluates the test expression.


● If the test expression is true, codes inside the body of while loop is
evaluated.
● Then, the test expression is evaluated again. This process goes on until the
test expression is false.
● When the test expression is false, while loop is terminated.
Syntax
while
(testExpression)
{
// codes
}
Example
I=0;
while (i<=5)
{
Cout<<” SRM IST”
i++;
}
Do While Loop

The do...while loop is a variant of the while loop with one important difference.
The body of do...while loop is executed once before the test expression is checked.

● The codes inside the body of loop is executed at least once. Then, only the
test expression is checked.
● If the test expression is true, the body of loop is executed. This process
continues until the test expression becomes false.
● When the test expression is false, do...while loop is terminated.
Syntax

do
{
// codes;
}
while (testExpression);
Example
do
{
Cout<<”SRM IST “;
}
while (i<=5);

Example Program

Sum of n num (Lab program)

3. Datatypes in C++
1. Primary(Built-in) Data Types:
⮚ character
⮚ integer
⮚ floating point
⮚ boolean
⮚ double floating point
⮚ void
⮚ wide character

2.User Defined Data Types:

⮚ Structure
⮚ Union
⮚ Class
⮚ Enumeration
3.Derived Data Types:

⮚ Array
⮚ Function
⮚ Pointer

1.User Define Data type

The data types that are defined by the user are called the derived datatype or
user-defined derived data type.

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.

Structure:
A structure is a user defined data type in C/C++. A structure
creates a data type that can be used to group items of possibly different types into a
single type.
Syntax
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

Union:

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.

Syntax

union address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

Enumeration:

Enumeration (or enum) is a user defined data type in C. It is


mainly used to assign names to integral constants, the names make a
program easy to read and maintain.

Syntax

enum week
{
Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun
};
2.Built in Data Type

Data types in C++ is mainly divided into two types: Primitive Data Types:
These data typesare built-in or predefined data types and can be used directly by
the user to declare variables. example: int, char , float, bool etc.
:
These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char , float, bool etc.
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. Double variables typically requires 8 byte of
memory space.
void: Void means without any value. void datatype represents a valueless
entity. Void data type is used for those function which does not returns a value.

3.Derived data types

1. Array
2. Function
3. Pointer
Array
An array is simply a collection of variables of the same data
type that are referenced by a common name. In other words, when elements of
linear structures are represented in the memory by means of contiguous memory
locations, these linear structures are called arrays.

An array stores a list of finite number (n) of homogeneous


data elements (i.e., data elements of the same type). The number n is called length
or size or range of an array.

Syntax

type array_name[array_size];

Example

Int arr[10];

Functions
A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of the
function. The C++ standard library provides numerous built-in functions that your
program can call.
Function prototype or function interface is a declaration of
a function that specifies the function's name and type signature (arity, data types
of parameters, and return type), but omits the function body.

Syntax

Function name ()
{
--------
--------
}

Pointers

& symbol is used to get the address of the variable. * symbol is used
to get the value of the variable that the pointer is pointing to. If a pointer in C is
assigned to NULL, it means it is pointing to nothing. Two pointers can be
subtracted to know how many elements are available between these two pointers.

The actual data type of the value of all pointers, whether integer,
float, character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that
the pointer points to.

Syntax

Int *a

4.Operators in C++
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

Arithmetic Operators

Operato Description Example


r

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200


/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after B % A will give 0


an integer division

++ Increment operator, increases integer value A++ will give 11


by one

-- Decrement operator, decreases integer A-- will give 9


value by one

Relational Operators

Operato Description Example


r

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition becomes
true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand, if
yes then condition becomes true.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of right
operand, if yes then condition becomes
true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right operand,
if yes then condition becomes true.

Logical Operators
Operato Description Example
r

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is t


reverses the logical state of its operand. If a
condition is true, then Logical NOT
operator will make false.

Bitwise Operators
Operator Description Example Operator Description

& Binary AND Operator & Binary AND Operator


copies a bit to the (A & B) will give 12 copies a bit to the
result if it exists in which is 0000 1100 result if it exists in
both operands. both operands.
| Binary OR Operator (A | B) will give 61 | Binary OR Operator
copies a bit if it exists which is 0011 1101 copies a bit if it exists
in either operand. in either operand.

^ Binary XOR Operator ^ Binary XOR Operator


copies the bit if it is set (A ^ B) will give 49 copies the bit if it is set
in one operand but not which is 0011 0001 in one operand but not
both. both.

~ Binary Ones (~A ) will give -61 ~ Binary Ones


Complement Operator which is 1100 0011 in 2's Complement Operator
is unary and has the complement form due to is unary and has the
effect of 'flipping' bits. a signed binary number. effect of 'flipping' bits.

Assignment Operators
Operato Description Example
r

= Simple assignment operator, Assigns values C = A + B will assign value of A + B


from right side operands to left side operand. into C

+= Add AND assignment operator, It adds right


operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand.

-= Subtract AND assignment operator, It


subtracts right operand from the left operand C -= A is equivalent to C = C - A
and assign the result to left operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left operand.
/= Divide AND assignment operator, It divides
left operand with the right operand and assign C /= A is equivalent to C = C / A
the result to left operand.

%= Modulus AND assignment operator, It takes


modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.

Misc Operators
Sr.No Operator & Description

1 sizeof
sizeof 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.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes, structures, and
unions.

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.

Unit 3
1.Functions in C++
A function is a group of statements that together perform a task.
Every C++program has at least one function, which is main(), and all the most
trivial programs can define additional functions. ... A function declaration tells the
compiler about afunction's name, return type, and parameters.

Syntax:

return-type function-name(parameter1, parameter2, ...)

// function-body

● return-type: suggests what the function will return. It can be int, char, some
pointer or even a class object. There can be functions which does not return
anything, they are mentioned with void.
● Function Name: is the name of the function, using the function name it is
called.
● Parameters: are variables to hold values of arguments passed while
function is called. A function may or may not contain parameter list.
● Function body: is the part where the code statements are written.

Declaring, Defining and Calling a Function

#include < iostream>


using namespace std;
int sum (int x, int y); -------🡪//declaring the function
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); -------🡪calling the function
cout << c;
}
int sum (int x, int y) -------🡪defining the function
{
return (x + y);
}

Calling a Function
Functions are called by their names. If the function is without argument, it can
be called directly using its name. But for functions with arguments, we have two
ways to call them,

1. Call by Value
2. Call by Reference

Call by Value
In this calling technique we pass the values of arguments which are stored or
copied into the formal parameters of functions. Hence, the original values are
unchanged only the parameters inside function changes.
Example
void calc(int x);

int main()

int x = 10;
calc(x);

printf("%d", x);

void calc(int x)

x = x + 10 ;

Call by Reference
In this we pass the address of the variable as arguments. In this case the
formal parameter can be taken as a reference or a pointer, in both the case they will
change the values of the original variable
Example
void calc(int *p);

int main()

int x = 10;

calc(&x); // passing address of x as argument

printf("%d", x);

void calc(int *p)

*p = *p + 10;

Main Function
The main( ) function in a C++ program is typically a non value returning
function (a void function). A void function does not return a value to its caller.
the main function is "called" by the operating system when the user runs the
program.

When a C++ program is executed, the execution control goes directly to


the main() function. Every C++ program have a main() function.

Syntax:

Void main

---------

-----------

Default arguments

In C++ programming, you can provide default values for function


parameters. The idea behind default argument is simple. If a function is called by
passingargument/s, those arguments are used by the function. But if the argument/s
are not passed while invoking a function then, the default values are used.

Example Program (Lab program Ex.No 6)

2.FUNCTION OVERLOADING

Function overloading is a feature in C++ where two or more functions can have
the same name but different parameters. Function overloading can be considered as an
example of polymorphism feature in C++

Two or more functions having same name but different argument(s) are
known as overloaded functions.

FUNCTION OVERLOADING
Function Overloading is when multiple function with same name exist in a
class. Function Overriding is when function have same prototype in base class as
well as derived class. Function overloading is a compile-time polymorphism.

Rules

● The same function name is used for more than one function definition
● The functions must differ either by the arity or types of their parameters

Example

Class aaa

Sum(int a, Int b) // same function name & different parameter

Sum(float x,int z)

Example Program

#include <iostream>

class Addition

public:

int sum(int num1,int num2)

return num1+num2;

int sum(int num1,int num2, int num3)


{

return num1+num2+num3;

};

int main(void)

Addition obj;

cout<<obj.sum(20, 15)<<endl;

cout<<obj.sum(81, 100, 10);

return 0;

FUNCTION OVERRIDING

Function Overloading can occur without inheritance. Function Overriding


occurs when one class is inherited from another class.

Example

int test() { }

int test(int a) { }

float test(double a) { }

int test(int a, double b) { }

Example program : Lab Program Ex .no 7

#include <iostream.h>
class printData
{
public:
void print(int i)
{
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};

int main()
{
printData pd;
pd.print(5);
pd.print(500.263);
pd.print("Hello C++");
return 0;
}
OUTPUT
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
3.Class and object

Class

C++ Classes and Objects. 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.

Syntax

Class class_name

Example

Class bca

Structure of the class .


● 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 defines the properties and behavior 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 be apply brakes, increase
speed etc
Object
An object is an instantiation of a class. In terms of variables, a class
would be the type, and an object would be the variable. In the class-based
object-oriented programming paradigm, "object" refers to a
particular instance of a class where the object can be a combination of
variables, functions, and data structures..
Syntax

Class_name object-name

Example

Bca aa;
Member function Definition

There are 2 ways to define a member function:


● Inside class definition
● Outside class definition
Inside class

class bca
{
public :
int a,b,c:;
sum() // function definition
{
c=a+b;
}
};

Outside class

class bca
{
public :
int a,b,c:;
sum() // function Declaration
};
void bca :: sum() // function definition
{
c=a+b;
}
To define a member function outside the class definition we have to use the
scope resolution :: operator along with class name and function name.

Array of object

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

Syntax

class class-name

datatype var1;

datatype varN;

method1();

method2();

methodN();

};

class-name obj[ size ];

Example

Class aaa

Void main()

{
Aaa a1[5] // array of object

Example program

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
Classemp
{
inteid;
doublehra, pf, da, cca, nf, bp;
charename[10];
public:
voidgetdata()
{
cout<<”enter name of the employee:”<<endl;
gets(name);
cout<<”enter employee id:”<<endl;
cin>>eid;
cout<<”enter employee basic pay:”<<endl;
cin>>bp;
}
void allow()
{
hra=(bp*10)/100;
pf=(bp*12)/100;
da=(bp*11)/100;
cca=(bp*8)/100;
np=(bp+hra+da+cca)-pf;
}
Voidputdata();
{
cout<<”employee name is:”<<ename<<endl;
cout<<”employee id is:”<<eid<<endl;
cout<<”employee basic pay is:”<<bp<<endl;
cout<<”\nhra=”<<hra<<”\n da=”<<da<<”\n pf=”<<pf<<”\n
cca=”<<cca;
cout<<”\n net pay of employee is:”<<np<<endl;
}
};
void main()
{
clrscr();
int n;
emp e[100];
cout<<”\n \t Arrays Of Objects”;
cout<<”\n enter number of employees:”<<endl;
cin>>n;
for(inti=0;i<n;i++)
{
cout<<”entering the details of employee:”<<i+1<<endl;
e[i].getdata();
e[i].allow();
}
clrscr();
for(inti=0;i<n;i++)
{
cout<<”displaying details of employee:”<<i+1<<endl;
e[i].putdata();
cout<<endl;
}
getch();
}
OUTPUT:

Arrays Of Objects

enter number of employees: 1


entering the details of employee:1
enter name of the employee: xyz
enter employee id:200
enter employee basic pay:1000
displaying details of employee: 1
employee name is: xyz
employee id is:200
employee basic pay is:1000
hra=100
da=110
pf=120
cca=80
net pay of employee is:1170
4. FRIEND FUNCTION IN C++
A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.
A friend can be a function, function template, or member function, or a class
or class template, in which case the entire class and all of its members are friends.

To declare a function as a friend of a class, precede the function prototype in


the class definition with keyword friend.

Syntax

friend function-name()

Example

class Box

double a;

public:

double b;

friend sum();

};
Example Program:
#include <iostream.h>
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { }
friend int add(A, B);
};
class B
{
private:
int numB;
public:
B(): numB(1) { }
friend int add(A , B);
};
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
5. Constructor and Destructorin C++

● Constructor has same name as the class itself.


● Constructors don't have return type.
● A constructor is automatically called when an object is created.
● If we do not specify a constructor, C++ compiler generates a
default constructor for us (expects no parameters and has an empty body).
Uses

The 'calling part' is performed automatically whenever a new Object of the class
is created. Constructors can be used for efficient memory management, which is
not possible with functions. Destructor can be used to destroy
the constructors when not needed.
Syntax:
Class classname
public:

class Name()

{
//set fields and call methods
}
Example
Class bca
{
Bca ()
{
Cout << “Welcome;
}
};
Void main()
{
Bca b; // Constructor will call Automatically
}

Constructor overloading
Constructor overloading in C++ programming is same as function overloading.
When we create more that one constructors in a class with different number of parameters
or different types of parameters or different order of parameters, it is called as constructor
overloading
Types of Constructor

Constructors are of three types:

⮚ Default Constructor.
⮚ Parameterized Constructor.
⮚ Copy Constructor.
Default Constructor.

Default Constructors: Default constructor is the constructor which doesn't


take any argument. It has no parameters. .
Default constructor for a class as a constructor that can be called with no
arguments (this includes a constructor whose parameters all have default
arguments)
Syntax:

constructor_name ( ) ; // Declaration

class_name :: class_name ( ) //Defination

{
------ // Body of the constructor
}
Parameterized constructor

An object is declared in a parameterized constructor, the initial values have


to be passed as arguments to the constructor function. The normal way of object
declaration may not work. Theconstructors can be called explicitly or implicitly.

Syntax

constructor_name (int x, int y ) ; // Declaration

class_name :: class_name (int x, int y ) //Defination

{
------ // Body of the constructor
}

Copy Constructor

Generally in a constructor the object of its own class can’t be passed as a


value parameter. But the classes own object can be passed as a reference parameter.

Such constructor having reference to the object of its own class is known as
copy constructor. It creates a new object as a copy of an existing object.

Syntax

class class_name{
public:
class_name(class_name & obj)
{
// obj is same class another object
// Copy Constructor code
}
//... other Variables & Functions
}
Example

Main ()
{
class_name object1(params);
Method 1 - Copy Constrcutor
class_name object2(object1);
Method 2 - Copy Constrcutor
class_name object3 = object1;
}
Destructor

A destructor is a member function with the same name as its class prefixed
by a ~ (tilde).
A destructor is a special method called automatically during the destruction
of an object. Actions executed in the destructor include the following: Recovering
the heap space allocated during the lifetime of an object.
Basically Constructor is used to initialize the objects (at the time of
creation), and they are automatically invoked. This saves us from the garbage
values assigned to data members; during initializing.

Syntax:
Class class_name
{
public:
~class_name() //Destructor
{
}
}:
Example
Class bca
{
public:
~bca() //Destructor
{
}
}:

Unit 4

1 -Inheritance

Inheritance is the process of creating new classes, called derived classes,


from existing classes or base classes. The derived class inherits all the capabilities
of the base class.

An inherited class is called a subclass of its parent class or super class.

Inheritance is a mechanism in which one class acquires the property of


another class. For example, a child inherits the traits of his/her parents.
With inheritance, we can reuse the fields and methods of the existing class.

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.

(Parent class, Super class, Base class)

(Child class, Sub class, Derived class)

Syntax

class subclass_name : access_mode base class_name


{
//body of subclass
};
Example
Class A
{
-------
};
class B : public A
{
-------
};
Types of Inheritance

!.Single Inheritance

2. Multilevel Inheritance

3. Multiple Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance

Single Inheritance

(One base class -One derived class)

Single Inheritance have One base class and One derived class C++ single
inheritance only one class can be derived from the base class. Based on the
visibility mode used or access specify used while deriving, the properties of the
base class are derived. Accesses specify can be private, protected or public.

Diagram
Example

Class A // base class

{ ..........

};

Class B: acess_specifier A // derived class

{ ...........

};

Multilevel Inheritance

(One Base - One Derived - One or more than One Intermediate class)

Multilevel Inheritance in C++ Programming. When a class is derived from a


class which is also derived from another class, i.e. a class having more than one
parent classes, such inheritance is called Multilevel Inheritance. The level of
inheritance can be extended to any number of level depending upon the relation.

Diagram
class A // base class

{ ...........

};

class B : acess_specifier A // derived class

{ ...........

};

class C : access_specifier B // derived from derived class B

{ ...........

};

Multiple Inheritance

More than One base class -One derived class

Multiple Inheritance in C++ Multiple Inheritance is a feature of C++ where a


class can inherit from more than one classes. The constructors of inherited classes
are called in the same order in which they are inherited

Diagram
Syntax

class A
{..........
};
class B
{ ...........
};
class C : acess_specifier A , access_specifier B // derived class from A and B
{...........
};
Difference between Multilevel and Multiple Inheritance

● Multilevel inheritance : Inheritance of characters by a child from father and


father inheriting characters from his father (grandfather)
● Multiple inheritance : Inheritance of characters by a child from mother and
father

Hierarchical Inheritance

One base class - More than One Derived class


Several classes are derived from common base class it is called hierarchical
inheritance.

In C++ hierarchical inheritance, the feature of the base class is inherited


onto more than one sub-class.

Diagram

Syntax
class A // base class
{..............
};
class B : access_specifier A // derived class from A
{ ...........
};
class C : access_specifier A // derived class from A
{ ...........
};
class D : access_specifier A // derived class from A
{ ...........
};
Hybrid Inheritance
Combination of More than One type of Inheritance
C++ hybrid inheritance is combination of two or more types of inheritance.
It can also be called multi path inheritance.
The hybrid combination of single inheritance and multiple inheritance.
Hybrid inheritance is used in a situation where we need to apply more than one
inheritance in a program.
Diagram

Syntax
class A
{ .........
};
class B : public A
{ ..........
};
class C
{ ...........
};
class D : public B, public C
{ ...........
};
Example program -Lab Program (9,10,11,12) Any one
2.Virtual Base class
Virtual base class is used in situation where a derived have multiple copies
of base class.

Two or more objects are derived from a common base class, we can prevent
multiple copies of the base class being present in an object derived from those
objects by declaring the base class as virtual when it is being inherited. Such a base
class is known as virtual base class. This can be achieved by preceding the base
class’ name with the word virtual.
Syntax
class A
{
}
class B: Virtual public A //virtual base class
{
}
class C: Virtual public A // virtual base class
{
{
}
class D: public B, public C
{
}
Example Program :

#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : virtual public ClassA
{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};
class ClassD : public ClassB, public ClassC
{
public:
int d;
};

void main()
{
ClassD obj;
obj.a = 10; //Statement 1
obj.a = 100; //Statement 2
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;

Output :
A : 100
B : 20
C : 30
D : 40

3.Virtual Function

A virtual function is a member function that you expect to be redefined in


derived classes. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and
execute the derived class's version of the function.
Uses
virtual functions when you want to override a certain behavior (read method)
for your derived class rather than the one implemented for the base class and you
want to do so at run-time through a pointer to the base class.
Rules for calling virtual Function
1. When a virtual function in a base class is a created, there must be definition of a
virtual function in the base class.
2. They cannot be static member.
3. They can be friend function to another class.
4. They are accessed using object pointer.
5. A base pointer can serve as a pointer to derived object since it is type compatible
where as a derived object pointer variable to base object.

Syntax
class class- name
{
public:
virtual function-name()
{
}
};
Example
class bca
{
public:
virtual sum() // virtual function
{
}
};
Example program
#include <iostream.h>
class Bird
{
public:
virtual void features()
{
cout << "Loading Bird features.\n";
}
};
class Parrot : public Bird
{
public:
void features()
{
this->Bird::features();
cout << "Loading Parrot features.\n";
}
};
class Penguin : public Bird
{
public:
void features()
{
this->Bird::features();
cout << "Loading Penguin features.\n";
}
};
class Loader
{
public:
void loadFeatures(Bird *bird)
{
bird->features();
}
};
int main()
{
Loader *l = new Loader;
Bird *b;
Parrot p1;
Penguin p2;
b = &p1;
l->loadFeatures(b);
b = &p2;
l->loadFeatures(b);
return 0;
}
OUTPUT
Loading Bird features.
Loading Parrot features.
Loading Bird features.
Loading Penguin features.

4. Abstract class and Pure virtual Function

An abstract class is a class that is designed to be specifically used as a base


class. An abstract class contains at least one pure virtual function. You declare a
pure virtual function by using a pure specifier ( = 0 ) in the declaration of a virtual
member function in the class declaration.
A class that is declared using “abstract” keyword is known as abstract class.
It can have abstract methods(methods without body) as well as concrete methods
(regular methods with body).
An abstract class cannot be instantiated, which means you are not allowed to
create an object of it.
An abstract class is mostly used to provide a base for subclasses to
extend and implement the abstract methods and override or use the implemented
methods in abstract class.
Pure virtual Function

A pure virtual function or pure virtual method is a virtual function that is


required to be implemented by a derived class if the derived class is not abstract.
Classes containing pure virtual methods are termed "abstract" and they cannot be
instantiated directly.

A subclass of an abstract class can only be instantiated directly if all


inherited pure virtual methods have been implemented by that class or a parent
class.

Example
Class student /*abstract class*/
{
Virtual void sum()=0; /*pure virtual function*/
};
Example
class Test // abstract class
{
public:
virtual void show() = 0;
};
Pure virtual function is also known as abstract class.

● We can't create an object of abstract class b'coz it has partial implementation


of methods.
● Abstract function doesn't have body
● We must implement all abstract functions in derived class.

Example Program

#include<iostream.h>

#include<conio.h>

class BaseClass //Abstract class

public:

virtual void Display1()=0; //Pure virtual function or abstract function

virtual void Display2()=0; //Pure virtual function or abstract function

void Display3()

cout<<"\n\tThis is Display3() method of Base Class";

};

class DerivedClass : public BaseClass

public:

void Display1()

cout<<"\n\tThis is Display1() method of Derived Class";

}
void Display2()

cout<<"\n\tThis is Display2() method of Derived Class"

};

void main()

DerivedClass D;

D.Display1(); // This will invoke Display1() method of Derived Class

D.Display2(); // This will invoke Display2() method of Derived Class

D.Display3(); // This will invoke Display3() method of Base Class

Output :

This is Display1() method of Derived Class

This is Display2() method of Derived Class

This is Display3() method of Base Class

5. This Pointer

C++ this Pointer. Every object in C++ has access to its own address
through an important pointer called this pointer. This pointer is an implicit
parameter to all member functions. ... Friend functions do not have a
this pointer, because friends are not members of a class.

A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.

Uses

1. Each object gets its own copy of the data member.


2. 2. All access the same function definition as present in the code
segment.

The ‘this’ pointer is passed as a hidden argument to all non-static


member function calls and is available as a local variable within the body of all
non-static functions.

‘this’ pointer is a constant pointer that holds the memory address of the
current object. ‘this’ pointer is not available in static member functions as static
member functions can be called without any object (with class name).

The this pointer holds the address of current object, in simple words you
can say that this pointer points to the current object of the class
Example Program:
#include <iostream.h>
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { }
friend int add(A, B);
};
class B
{
private:
int numB;
public:
B(): numB(1) { }
friend int add(A , B);
};
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
6.Operator overloading
In C++, we can make operators to work for user defined classes. This means C++
has the ability to provide the operators with a special meaning for a data type, this ability
is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +.

C++ provides a special function to change the current functionality of some


operators within its class which is often called as operator overloading. Operator
Overloading is the method by which we can change the function of some specific
operators to do some different task.
Syntax
Return_Type classname :: operator op(Argument list)
{
Function Body
}

Operator Overloading can be done by using three approaches, they are

1. Overloading unary operator.


2. Overloading binary operator.
Overloading Unary Operator: Let us consider to overload (-) unary operator. In
unary operator function, no arguments should be passed. It works only with one class
objects. It is a overloading of an operator operating on a single operand.
Overloading Binary Operator: In binary operator overloading function, there
should be one argument to be passed. It is overloading of an operator operating on two
operands.
Rules for overloading
● In case of a non-static function, the binary operator should have only one argument
and unary should not have an argument.
● In the case of a friend function, the binary operator should have only two argument
and unary should have only one argument.
● All the class member object should be public if operator overloading is
implemented.

Operators which cannot be overloaded.


● ?: (conditional)
● . ( member selection)
● .* (member selection with pointer-to-member)
● :: (scope resolution)
● sizeof (object size information)
● typeid (object type information)
● static_cast (casting operator)
● const_cast (casting operator)

Overloaded Operators

Example Program
#include <iostream.h>
using namespace std;

class IncreDecre
{
int a, b;
public:
void accept()
{
cout<<"\n Enter Two Numbers : \n";
cout<<" ";
cin>>a;
cout<<" ";
cin>>b;
}
void operator--() //Overload Unary Decrement
{
a--;
b--;
}
void operator++() //Overload Unary Increment
{
a++;
b++;
}
void display()
{
cout<<"\n A : "<<a;
cout<<"\n B : "<<b;
}
};
int main()
{
IncreDecre id;
id.accept();
--id;
cout<<"\n After Decrementing : ";
id.display();
++id;
++id;
cout<<"\n\n After Incrementing : ";
id.display();
return 0;
}

UNIT 5
1.C++ Stream classes
In C++ there are number of stream classes for defining various streams
related with files and for doing input-output operations. All these classes are
defined in the file iostream.h.
1. ios class is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.

2. istream and ostream serves the base classes for iostream class. The class istream is
used for input and ostream for the output.

3. Class ios is indirectly inherited to iostream class using istream and ostream. To avoid
the duplicity of data and member functions of ios class, it is declared as virtual base class
when inheriting in istream and ostream as

Syantax

class istream: virtual public ios

};

class ostream: virtual public ios


{

};

4. The withassign classes are provided with extra functionality for the assignment
operations that’s why _withassign classes.

5. The ios class: The ios class is responsible for providing all input and output facilities
to all other stream classes.
6.The istream class: This class is responsible for handling input stream. It provides
number of function for handling chars, strings and objects such as get, getline, read,
ignore, putback etc..
Example Program
#include <iostream>
using namespace std;

int main()
{
char x;

// used to scan a single char


cin.get(x);

cout << x;
}
2.C++ stream
C++ comes with libraries which provides us with many ways for performing input and
output. In C++ input and output is performed in the form of a sequence of bytes or more
commonly known as streams.
The most basic stream types are the standard input/output streams: istream cin. built-in
input stream variable; by default hooked to keyboard. ostream cout built-in
output stream variable; by default hooked to console.
● Input Stream: If the direction of flow of bytes is from the device(for example,
Keyboard) to the main memory then this process is called input.
● Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory
to device ( display screen ) then this process is called output.

3.Unformatted I/O
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. It is a method of cout
object and it is used to print the specified character on the screen or monitor.
Unformatted Input/Output is the most basic form of
input/output. Unformatted input/output transfers the internal binary representation of the
data directly between memory and the file. Formatted output converts the internal binary
representation of the data to ASCII characters which are written to the output file

Unformatted consol input output operations

1.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();

2.void put()

It is a method of cout object and it is used to print the specified character on the screen or
monitor.

Syntax:

cout.put(variable / character);

3.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);

4.write(char * buffer, int n)

It is a method of cout object. This method is used to read n character from buffer variable.

Syntax:

cout.write(x,2);

5.cin
It is the method to take input any variable / character / string.

Syntax:

cin>>variable / character / String / ;

6.cout

This method is used to print variable / string / character.

Syntax:

cout<< variable / charcter / string;

4.Formatted console input output operations


The difference between formatted and unformatted input and output operations
is that in case of formatted I/O the data is formatted or transformed. Unformatted
I/O transfers data in its raw form or binary representation without any conversions. ...
putchar() function will print a single character on standard output.

In formatted console input output operations we uses following functions to


make output in perfect alignment. In industrial programming all the output should be
perfectly formatted due to this reason C++ provides many function to convert any file
into perfect aligned format

1.width(n)

This function is used to set width of the output.

Syntax:

cout<<setw(int n);

2.fill(char)

This function is used to fill specified character at unused space.

Syntax:

cout<<setfill('character')<<variable;
3.precison(n)

This method is used for setting floating point of the output.

Syntax:

cout<<setprecision('int n')<<variable;

4.setflag(arg 1, arg,2)

This function is used for setting format flags for output.

Syntax:

setiosflags(argument 1, argument 2);

5. unsetflag(arg 2)

This function is used to reset set flags for output.

Syntax:

resetiosflags(argument 2);

6.setbase(arg)

This function is used to set basefield of the flag.

Syntax:

setbase(argument);

5.Exception Handling

An exception is a problem that arises during the execution of a program. A C++


exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
Exception handling in C++ is built on three keywords: try, catch, and throw.
throw: A program throws an exception when a problem is detected which is done using a
keyword "throw". catch: A program catches an exception with an exception
handler where programmers want to handle the anomaly.

Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.

● throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
● catch − A program catches an exception with an exception handler at the place in
a program where you want to handle the problem. The catch keyword indicates
the catching of an exception.
● try − A try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords

Syntax

try {

// protected code

} catch( ExceptionName e1 ) {

// catch block

} catch( ExceptionName e2 ) {

// catch block

} catch( ExceptionName eN ) {

// catch block

}
Throwing Exceptions

Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can be any
expression and the type of the result of the expression determines the type of exception
thrown.

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.

Try
{
// protected code
}
catch()
{
// code to handle ExceptionName exception
}

Example Program

#include <iostream>

using namespace std;

double division(int a, int b) {

if( b == 0 ) {

throw "Division by zero condition!";


}

return (a/b);

int main ()

int x = 50;

int y = 0;

double z = 0;

try {

z = division(x, y);

cout << z << endl;

catch (const char* msg)

cerr << msg << endl;

return 0;

You might also like