CPP 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

C++ Unit -2

Operators Overloading

Operator overloading is a compile-time polymorphism in which the operator is overloaded to


provide the special meaning to the user-defined data type. Operator overloading is used to
overload or redefines most of the operators available in C++. It is used to perform the operation
on the user-defined data type. For example, C++ provides the ability to add the variables of the
user-defined data type that is applied to the built-in data types.

The advantage of Operators overloading is to perform different operations on the same operand.

Syntax of Operator Overloading


return_type class_name : : operator op(argument_list)
{ // body of the function. }
Where the return type is the type of value returned by the function.
class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the operator
is the keyword.
Rules for Operator Overloading
o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.

#include <iostream.h>
class Test
{ private:
int num;
public:
Test(): num(8){}
void operator ++()
{ num = num+2; }
void Print()
{ cout<<"The Count is: "<<num; }
};
main()
{ Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
}
Output:
The Count is: 10
Program to overload the binary operators.

#include <iostream.h>
class A
{ int x;
public:
A(){}
A(int i)
{ x=i; }
void operator+(A);
void display();
};

void A :: operator+(A a)
{
int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{ A a1(5);
A a2(4);
a1+a2;
return 0;
}

Output:
The result of the addition of two objects is : 9

Overloadable/Non-overloadableOperators

Following is the list of operators which can be overloaded –

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

Following is the list of operators, which can not be overloaded −

:: .* . ?:
Passing object as parameter in operator overloading
#include<iostream.h>

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {real = r; imag = i;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << '\n'; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9

Type Conversion

A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
 All the data types of the variables are upgraded to the data type of the variable with
largest data type.
 bool -> char -> short int -> int ->

 unsigned int -> long -> unsigned ->


 long long -> float -> double -> long double
 It is possible for implicit conversions to lose information, signs can be lost (when signed
is implicitly converted to unsigned), and overflow can occur (when long long is
implicitly converted to float).
#include <iostream.h>
main()
{
int x = 10; // integer x
char y = 'a'; // character c
x = x + y;
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
}
Output:
x = 107
y=a
z = 108

Explicit Type Conversion: This process is also called type casting and it is user-defined. Here
the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
Converting by assignment: This is done by explicitly defining the required type in front of
the expression in parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;
cout << "Sum = " << sum;

return 0;
}
Output:
Sum = 2
Conversion using Cast operator: A Cast operator is an unary operator which forces one data
type to be converted into another data type.

#include <iostream.h>
int main()
{ float f = 3.5;
int b = static_cast<int>(f);
cout << b;
}
Output: 3
Advantages of Type Conversion:
 This is done to take advantage of certain features of type hierarchies or type representations.
 It helps to compute expressions containing variables of different data types.

Inheritance
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature 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.
Modes of Inheritance

1. Public mode: If we derive a sub class from a public base class. Then the public member of
the base class will become public in the derived class and protected members of the base
class will become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then both public
member and protected members of the base class will become protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both public member
and protected members of the base class will become Private in derived class.

class A
{ public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{ // x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{ // x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
{ // x is private
// y is private
// z is not accessible from D
};
The below table summarizes the above three modes and shows the access specifier of the
members of base class in the sub class when derived in public, protected and private modes:

Types of Inheritance
1. 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.

#include <iostream.h>
// base class
class Vehicle {
public:
Vehicle()
{ cout << "This is a Vehicle" << endl; }
};
class Car: public Vehicle
{ };
int main()
{
Car obj;
return 0;
}

Output:
This is a vehicle

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from
more than one classes. i.e one sub class is inherited from more than one base classes
classes.
#include <iostream>
// first base class
class Vehicle
{ public:
Vehicle()
{ cout << "This is a Vehicle" << endl; }
};
// second base class
class FourWheeler
{ public:
FourWheeler()
{ cout << "This is a 4 wheeler Vehicle" << endl; }
};
// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {
};
// main function
int main()
{ Car obj;
return 0;
}
Output:
This is a Vehicle
This is a 4 wheeler Vehicle

3. Multilevel Inheritance:: In this type of inheritance, a derived class is created from another
derived class.
4. Hierarchical Inheritance:: In this type of inheritance, more than one sub class is inherited
from a single base class. i.e. more than one derived class is created from a single base class.

Inheritance: Hybrid Inheritance is implemented by combining more than


5. Hybrid (Virtual) Inheritance:
one type of inheritance. For example: Combining Hierarchical inheritance and Multiple
Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:
Pointers
Pointers are symbolic representation of addresses. They enable programs to simulate
simulate call
call-by-
reference as well as to create and manipulate dynamic data structures. It’s general declaration in
C/C++ has the format:

How to use a pointer?


 Define a pointer variable
 Assigning the address of a variable to a pointer using unary operator (&) which returns the
address of that variable.
 Accessing the value stored in the address using unary operator (*) which returns the value
of the variable located at the address specified by its operand.
The reason we associate data type to a pointer is thatat it knows how many bytes the data is stored
in.. When we increment a pointer, we increase the pointer by the size of data type to which it
points.
NULL Pointers

Null pointerr is a pointer which point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;

1 Null Pointers
C++ supports null pointer, which is a constant with a value of zero defined in several standard
libraries.

2 Pointer Arithmetic
There
ere are four arithmetic operators that can be used on pointers: ++, --, +, -

3 Pointers vs Arrays
There is a close relationship between pointers and arrays.

4 Array of Pointers
You can define arrays to hold a number of pointers.

5 Pointer to Pointer
C++ allows you to have pointer on a pointer and so on.

6 Passing Pointers to Functions


Passing an argument by reference or by address both enable the passed argument to be
changed in the calling function by the called function.

7 Return Pointer from Functions


C++ allows a function to return a pointer to local variable, static variable and dynamically
allocated memory as well.
Virtual function
o A C++ virtual function is a member function in the base class that you redefine in a
derived class. It is declared using the virtual keyword.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
o There is a necessity to use the single pointer to refer to all the objects of the different
classes. So, we create the pointer to the base class that refers to all the derived objects.
But, when base class pointer contains the address of the derived class object, always
executes the base class function. This issue can only be resolved by using the 'virtual'
function.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o When the function is made virtual, C++ determines which function is to be invoked at the
runtime based on the type of the object pointed by the base class pointer.

Late binding or Dynamic linkage

In late binding function call is resolved during runtime. Therefore compiler determines the type
of object at runtime, and then binds the function call.

Rules of Virtual Function

o Virtual functions must be members of some class.


o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will
consider them as the overloaded functions.
o We cannot have a virtual constructor, but we can have a virtual destructor
o Consider the situation when we don't use the virtual keyword.

#include<iostream>
using namespace std;

class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print ()
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

int main()
{
base *bptr;
derived d;
bptr = &d;

//virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();
}
Output:
print derived class
show base class

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.
Real life example of polymorphism, 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.
Polymorphism is considered as one of the important features of Object Oriented Programming.

In C++ polymorphism is mainly divided into two types:

 Compile time Polymorphism


 Runtime Polymorphism

1. Compile time polymorphism: This type of polymorphism is achieved by function


overloading or operator overloading.

Function Overloading:
When there are multiple functions with same name but different parameters then these functions
are said to be overloaded. Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
#include <bits/stdc++.h>
class Geeks
{ public:

void func(int x)
{ cout << "value of x is " << x << endl; }
void func(double x)
{ cout << "value of x is " << x << endl; }
void func(int x, int y)
{ cout << "value of x and y is " << x << ", " << y << endl; }
};

int main() {
Geeks obj1;
// Which function is called will depend on the parameters passed
// The first 'func' is called
obj1.func(7);

// The second 'func' is called


obj1.func(9.132);
// The third 'func' is called
obj1.func(85,64);
return 0;
}

Output:
value of x is 7
value of x is 9.132
value of x and y is 85, 64

Operator Overloading:
C++ also provide option to overload operators. For example, we can make the operator (‘+’) for
string class to concatenate two strings. We know that this is the addition operator whose task is
to add two operands. So a single operator ‘+’ when placed between integer operands , adds them
and when placed between string operands, concatenates them.

#include<iostream>
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
12 + i9

Runtime polymorphism:
This type of polymorphism is achieved by Function Overriding.

 Function overriding on the other hand occurs when a derived class has a definition for one
of the member functions of the base class. That base function is said to be overridden.

#include <bits/stdc++.h>
class base
{ public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{ public:
void print () //print () is already virtual function in derived class, we could also declared as virtual void print ()
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};
main()
{ base *bptr;
derived d;
bptr = &d;
bptr->print();
bptr->show();
}
Output: print derived class
show base class
Managing Console I/O operations

Every program takes some data as input and generates processed data as an output following
the familiar input process output cycle. It is essential to know how to provide the input data
and present the results in the desired form. The use of the cin and cout is already known with
the operator >> and << for the input and output operations. In this article, we will discuss how
to control the way the output is printed.
C++ supports a rich set of I/O functions and operations. These functions use the
advanced features of C++ such as classes, derived classes, and virtual functions. It also
supports all of C’s set of I/O functions and therefore can be used in C++ programs, but their
use should be restrained due to two reasons.
1. I/O methods in C++ support the concept of OOPs.
2. I/O methods in C cannot handle the user-define data type such as class and object.
It uses the concept of stream and stream classes to implement its I/O operations with the
console and disk files.
C++ Stream

The I/O system in C++ is designed to work with a wide variety of devices including terminals,
disks, and tape drives. Although each device is very different, the I/O system supplies an
interface to the programmer that is independent of the actual device being accessed. This
interface is known as the stream.
 A stream is a sequence of bytes.
 The source stream that provides the data to the program is called the input stream.
 The destination stream that receives output from the program is called the output stream.
 The data in the input stream can come from the keyboard or any other input device.
 The data in the output stream can go to the screen or any other output device.

C++ contains several pre-defined streams that are automatically opened when a program
begins its execution. These include cin and cout. It is known that cin represents the input
stream connected to the standard input device (usually the keyboard) and cout represents the
output stream connected to the standard output device (usually the screen).

C++ Stream Classes

The C++ I/O system contains a hierarchy of classes that are used to define various streams to
deal with both the console and disk files. These classes are called stream classes. The hierarchy
of stream classes used for input and output operations is with the console unit. These classes
are declared in the header file iostream. This file should be included in all the programs that
communicate with the console unit.

Advantages of Stream Classes


 Stream classes have good error handling capabilities.
 These classes work as an abstraction for the user that means the internal operation is
encapsulated from the user.
 These classes are buffered and do not uses the memory disk space.
 These classes have various functions that make reading or writing a sequence of bytes easy for
the programmer.
FILES

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
fstream headerfile.

ofstream: Stream class to write on files


ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

Now the first step to open the particular file for read or write operation. We can open file by

1. passing file name in constructor at the time of object creation


2. using the open method

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.

Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstreamobject may be used to open a file for writing. And ifstream object is
used to open a file for reading purpose only.
void open(const char *filename, ios::openmode mode);

Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
void close();

Writing to a File
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of thecout object.

Reading from a File

You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is that
you use an ifstream or fstream object instead of the cin object.
Read and Write Example
Following is the C++ program which opens a file in reading and writing mode. After writing
information entered by the user to a file named afile.dat, the program reads information from the
file and outputs it onto the screen

#include <fstream.h>
#include <iostream.h>
int main () {
char data[100];
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
return 0;
}

Writing to the file


Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

eof()
You can detect when the end of the file is reached by using the member function eof() which has
prototype : int eof();

File Pointers
Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in
output mode file) which tells the current position in the file where reading or writing will takes
place. (A file pointer in this context is not like a C++ pointer but it works like a book-mark in a
book.). These pointers help attain random access in file. That means moving directly to any
location in the file instead of moving through it sequentially.
There may be situations where random access in the best choice. For example, if you have to
modify a value in record no 21, then using random access techniques, you can place the file
pointer at the beginning of record 21 and then straight-way process the record. If sequential
access is used, then you'll have to unnecessarily go through first twenty records in order to reach
at record 21.

The seekg(), seekp(), tellg() and tellp() Functions

In C++, random access is achieved by manipulating seekg(), seekp(), tellg() and tellp() functions.
The seekg() and tellg() functions allow you to set and examine the get_pointer, and the seekp()
and tellp() functions perform these operations on the put_pointer.

The seekg() and tellg() functions are for input streams (ifstream) and seekp() and tellp()
functions are for output streams (ofstream). However, if you use them with an fstream object
then tellg() and tellp() return the same value. Also seekg() and seekp() work the same way in an
fstream object. The most common forms of these functions are :

istream & seekg(long); Form 1


seekg()
istream & seekg(long, seek_dir); Form 2

ofstream & seekp(long); Form 1


seekp()
ofstream & seekp(long, seek_dir); Form 2

tellg() long tellg()

tellp() long tellp()

The working of seekg() & seekp() and tellg() & tellp() is just the same except that seekg() and
tellg() work for ifstream objects and seekp() and tellp() work for ofstream objects. In the above
table, seek_dir takes the definition enum seek_dir { beg, cur, end};.

Error Handling during File Operations


Sometimes during file operations, errors may also creep in. For example, a file being opened for
reading might not exist. Or a file name used for a new file may already exist. Or an attempt could
be made to read past the end-of-file. Or such as invalid operation may be performed. There might
not be enough space in the disk for storing data.

To check for such errors and to ensure smooth processing, C++ file streams inherit 'stream-state'
members from the ios class that store the information on the status of a file that is being currently
used. The current state of the I/O system is held in an integer, in which the following flags are
encoded :
Name Meaning

eofbit 1 when end-of-file is encountered, 0 otherwise.

failbit 1 when a non-fatal I/O error has occurred, 0 otherwise

badbit 1 when a fatal I/O error has occurred, 0 otherwise

goodbit 0 value
Error Handling Functions
There are several error handling functions supported by class ios that help you read
and process the status recorded in a file stream.
Following table lists these error handling functions and their meaning :
Function Meaning

Returns a non-zero value if an invalid operation is attempted or any


int bad() unrecoverable error has occurred. However, if it is zero (false value), it may be
possible to recover from any other error reported and continue operations.

Returns non-zero (true value) if end-of-file is encountered while reading;


int eof()
otherwise returns zero (false value).

int fail() Returns non-zero (true) when an input or output operation has failed.

Returns non-zero (true) if no error has occurred. This means, all the above
functions are false. For example, if fin.good() is true, everything is okay with
int good()
the stream named as fin and we can proceed to perform I/O operations. When it
returns zero, no further operations can be carried out.

clear() Resets the error state so that further operations can be attempted.

The above functions can be summarized as eof() returns true if eofbit is set; bad() returns true if
badbit is set. The fail() function returns true if failbit is set; the good() returns true there are no
errors. Otherwise, they return false.

These functions may be used in the appropriate places in a program to locate the status of a file
stream and thereby take the necessary corrective measures

Command-line Arguments
The most important function of C/C++ is main() function. It is mostly defined with a return type
of int and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C and C++. Command-line arguments are given
after the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
 argc (ARGument Count) is int and stores number of command-line arguments passed by
the user including the name of the program. So if we pass a value to a program, value of
argc would be 2 (one for argument and one for program name)
 The value of argc should be non negative.
 argv(ARGument Vector) is array of character pointers listing all the arguments.
 If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
 Argv[0] is the name of the program , After that till argv[argc-1] every element is command
-line arguments.

#include <iostream>
using namespace std;

int main(int argc, char** argv)


{
cout << "You have entered " << argc
<< " arguments:" << "\n";

for (int i = 0; i < argc; ++i)


cout << argv[i] << "\n";

return 0;
}

Input:
$ g++ mainreturn.cpp -o main
$ ./main geeks for geeks

Output:
You have entered 4 arguments:
./main
geeks
for
geeks
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.
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. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch as follows −
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.
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.
Following is an example of throwing an exception when dividing by zero condition occurs −
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( ExceptionName e ) {
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a catch
block should handle any type of exception that is thrown in a try block, you must put an ellipsis,
..., between the parentheses enclosing the exception declaration as follows −
try {
// protected code
} catch(...) {
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it in catch
block.
#include <iostream.h>
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

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;
}
}
Because we are raising an exception of type const char*, so while catching this exception, we
have to use const char* in catch block. If we compile and run above code, this would produce the
following result −
Division by zero condition!
C++ Standard Exceptions
C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below −
Manipulating Strings
In C++, a string is a sequence of characters. As you know, C++ does not support the built-in
string type, and you have previously used null character-based terminated arrays to store and
manipulate strings. These strings are termed C Strings. C++ often becomes inefficient at
operating on strings. Programmers can also define their string classes with appropriate member
functions for manipulating strings. ANSI standard C++ introduces a new class called string,
an improvised version of C strings in several ways. In many cases, the string object may be
treated like any other built-in data type. The string is considered another container class for C++.

string class
The string class is vast and includes many constructors, member functions, and operators.
Programmers may use the constructors, operators, and member functions to achieve the
following:

 Creating string objects.


 Reading string objects from the keyboard.
 Displaying string objects on the screen.
 Finding a substring from a string.
 Modifying string.
 Adding objects of string.
 Comparing strings.
 Accessing characters of a string.
 Obtaining the size or length of a string, etc.

Manipulate Null-terminated Strings


C++ supports a wide range of functions that manipulate null-terminated strings. These are:
 strcpy(str1, str2): Copies string str2 into string str1.
 strcat(str1, str2): Concatenates string str2 onto the end of string str1.
 strlen(str1): Returns the length of string str1.
 strcmp(str1, str2): Returns 0 if str1 and str2 are the same; less than 0 if str1<str2; greater
than 0 if str1>str2.
 strchr(str1, ch): Returns a pointer to the first occurrence of character ch in string str1.
 strstr(str1, str2): Returns a pointer to the first occurrence of string str2 in string str1.

Important Functions Supported by String Class

 append(): This function appends a part of a string to another string.


 assign():This function assigns a partial string.
 at(): This function obtains the character stored at a specified location.
 begin(): This function returns a reference to the start of the string.
 capacity(): This function gives the total element that can be stored.
 compare(): This function compares a string against the invoking string.
 empty(): This function returns true if the string is empty.
 end(): This function returns a reference to the end of the string.
 erase(): This function removes characters as specified.
 find(): This function searches for the occurrence of a specified substring.
 length(): It gives the size of a string or the number of elements of a string.
 swap(): This function swaps the given string with the invoking one.

Important Constructors Obtained by String Class

 String(): This constructor is used for creating an empty string.


 String(const char *str): This constructor is used for creating string objects from a null-
terminated string.
 String(const string *str): This constructor is used for creating a string object from another
string object.

#include<iostream.h>
#include<string.h>
class string
{ char *name;
int length;
public:
string()
{ length=0;
name = new char[length+1];
}
string(char *n)
{ length=strlen(n);
name= new char [length+1];
strcpy(name,n);
}
void display()
{ cout<<"String:"<<name;}
string operator+(string s)
{ string temp;
strcpy(temp.name,name);
strcat(temp.name,s.name);
return temp;
}
};

int main()
{string s1("Hello");
string s2("Welcome");
string s3;
s1.display();
s2.display();
s3=s1+s2;
s3.display();
return 0;
}
Friend Class and Function
Friend Function
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
Like a friend class, a friend function can be granted special access to private and protected
members of a class in C++. They are the non-member functions that can access and manipulate
the private and protected members of the class for they are declared as friends.
Characteristics of a Friend function:
 The function is not in the scope of the class to which it has been declared as a friend.
 It cannot be called using the object as it is not in the scope of that class.
 It can be invoked like a normal function without using the object.
 It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
 It can be declared either in the private or the public part.

Friend class
A friend class can access both private and protected members of the class in which it has been
declared as friend.
#include <iostream> #include <iostream>
class B; using namespace std;
class A class Box
{ int x; { double width;
public: public:
void setdata(int i) friend void printWidth( Box box );
{ x=i; } void setWidth( double wid );
friend void min(A,B); }; };
class B void Box::setWidth( double wid )
{ int y; { width = wid; }
public:
void setdata(int i) void printWidth( Box box )
{ y=i; } { cout << "Width of box : " << box.width <endl; }
friend void min(A,B); }; main() {
void min(A a,B b) Box box;
{ if(a.x<=b.y) box.setWidth(10.0);
std::cout << a.x << std::endl; printWidth( box );
else return 0;
std::cout << b.y << std::endl; }
}
int main()
{ A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;
}

#include <iostream>
using namespace std;
class A
{ int x =5;
friend class B; // friend class.
};
class B
{ public:
void display(A &a)
{ cout<<"value of x is : "<<a.x; }
};
int main()
{ A a;
B b;
b.display(a);
return 0;
}

You might also like