CPP 2
CPP 2
CPP 2
Operators Overloading
The advantage of Operators overloading is to perform different operations on the same operand.
#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
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
:: .* . ?:
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;}
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 ->
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;
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.
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.
In late binding function call is resolved during runtime. Therefore compiler determines the type
of object at runtime, and then binds the function call.
#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;
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.
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);
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;}
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).
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.
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
fstream headerfile.
Now the first step to open the particular file for read or write operation. We can open file by
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.
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;
}
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.
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 :
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};.
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
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
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;
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:
#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;
}