Programming Methodologies with C++
Constructor, Parameterized Constructor, Multiple
Constructors in a Class
Study material
Index
S. No. Content
1. Objectives
2. Constructor
3. Parameterized Constructor
4. Multiple Constructors in a Class
5. Questions
6. References
1. Objectives
After studying this module the learner will be able to:
• Understand the use of a Constructor
• Create Parameterized Constructors
• Use Multiple Constructors in a Class
2. Constructors
■ Special member function which enables an object to initialize itself when it is created
■ Its name is same as the class name
■ Constructor definition outside class:
class integer
{ int m,n;
public:
integer(void);
……….
};
integer :: integer (void)
{ m=0; n=0;}
■ Constructor definition within class:
class integer
{ int m,n;
public:
integer(void)
{ m=0; n=0;}
……….
};
Characteristics of constructor:
■ They should be declared in the public section
■ They are invoked automatically when the objects are created
■ They do not have return types, not even void and therefore, and they cannot return
values
■ They cannot be inherited, though a derived class can call the base class
■ They can have default arguments
■ Constructors cannot be virtual functions
3. Parameterized Constructors
class integer
{ int m,n;
public:
integer (int x, int y);
……….
};
integer :: integer (int x, int y)
{
m=x;
n=y;
}
■ Explicit constructor call: integer int1=integer(1,2);
■ Implicit constructor call: integer int1(1,2);
4. Multiple Constructors in a Class
class code
{ int id;
public: code( ){ id=5;}
code (int a) { id=a; }
code( int a, int b) {id=a+b; }
};
In this class ‘code’ we have three constructors:
i) code(): This is a constructor with no parameters.
ii) code(int a): This is a constructor with one parameter.
iii) code(int a, int b): This is a constructor with two parameters.
Hence, multiple constructors may be used in a class as shown in the above code.
5. Questions
Q.1) What is a constructor? Why is it used?
Q.2) What are the rules for creating a constructor?
Q.3) How can parameterized constructors be implemented in C++?
Q.4) How can multiple constructors be implemented in C++?
Programming Methodologies with C++
Constructors with Default Arguments, Dynamic
Initialization of Objects, Copy Constructor,
Dynamic Constructor, Destructor
Study material
Index
S. No. Content
1. Objectives
2. Constructors with Default Arguments
3. Dynamic Initialization of Objects
4. Copy Constructor
5. Dynamic Constructor
6. Destructor
7. Questions
8. References
1. Objectives
After studying this module the learner will be able to:
• Create Constructors with Default Arguments
• Dynamically Initialize Objects
• Use Copy Constructor
• Use Dynamic Constructor
• Implement Destructor
2. Constructors with Default Arguments
class Demo
{ private:
int X,Y;
public:
Demo()
{ X = 0;
Y = 0;
cout << endl << "Constructor Called";
}
Demo(int X, int Y=20)
{
this->X = X;
this->Y = Y;
cout << endl << "Constructor Called";
}
void putValues()
{
cout << endl << "Value of X : " << X;
cout << endl << "Value of Y : " << Y << endl;
}
};
void main()
{
clrscr();
Demo d1= Demo(10);
cout << endl <<"D1 Value Are : ";
d1.putValues();
Demo d2= Demo(30,40);
cout << endl <<"D2 Value Are : ";
d2.putValues();
getch();
}
Output:
Constructor Called
D1 Value Are :
Value of X : 10
Value of Y : 20
Constructor Called
D2 Value Are :
Value of X : 30
Value of Y : 40
3. Dynamic Initialization of Objects
■ Dynamic initialization of object refers to initializing the objects at run time
■ The initial value of an object is to be provided during run time.
■ Dynamic initialization can be achieved using constructors and passing parameters
values to the constructors.
■ This type of initialization is required to initialize the class variables during run time.
class simple_interest
{ float principle , time, rate ,interest;
public: simple_interest (float a, float b, float c) {
principle = a;
time =b;
rate = c;
}
void display ( ) {
interest =(principle* rate* time)/100;
cout<<"Interest ="<<interest ;
}
};
void main(){
float p,r,t;
clrscr();
simple_interest s1(2000,7.5,2);
s1.display();
getch();
}
4. Copy Constructor
■ Used to declare and initialize an object from another object
integer I2(I1); or integer I2=I1;
■ Copy constructor takes a reference to an object of the same class as itself as an argument
5. Dynamic Constructor
■ Constructors can be used to allocate memory while creating objects
■ The memory is allocated with the help of new operator
■ Example:
class String
{ char *name;
int length;
public: String() {
length=0;
name=new char[length+1]; }
String(char *s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
void display()
{cout<<name<<“\n”;}
void join(String &a, String &b);
};
void String::join(String &a, String &b)
{ length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name,a.name);
strcpy(name,b.name);
}
void main()
{ char *first=“Ann ”;
String name1(first),name2(“Ben “),name3(“Joy”),s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display(); }
OUTPUT:
Ann
Ben
Joy
Ann Ben
Ann Ben Joy
6. Destructors
■ Member function used to destroy the objects that have been created by a constructor
~integer( ) { }
■ Never takes any argument
■ Never returns any value
■ Will be invoked implicitly by the compiler upon exit from the program/block/function
■ Example:
class Demo
{ private:
int X,Y;
public:
Demo()
{ X = 0;
Y = 0;
cout << endl << "Constructor Called";
}
Demo(int X, int Y=20)
{
this->X = X;
this->Y = Y;
cout << endl << "Constructor Called";
}
~Demo()
{
cout << endl << "Destructor Called" << endl;
}
void putValues()
{ cout << endl << "Value of X : " << X;
cout << endl << "Value of Y : " << Y << endl;
}
};
void main()
{
clrscr();
Demo d1= Demo(10);
cout << endl <<"D1 Value Are : ";
d1.putValues();
Demo d2= Demo(30,40);
cout << endl <<"D2 Value Are : ";
d2.putValues();
getch();
}
Output:
Constructor Called
D1 Value Are :
Value of X : 10
Value of Y : 20
Constructor Called
D2 Value Are :
Value of X : 30
Value of Y : 40
Destructor Called
Destructor Called
7. Questions
Q.1) How can constructors with default arguments be implemented in C++?
Q.2) How can objects be dynamically initialized?
Q.3) What is a Copy Constructor? Why is it used?
Q.4) What is a Dynamic Constructor? Why is it used?
Q.5) What are destructors? How can they be used in C++?
8. References
■ Let us C++, 2nd Edition, Yashawant Kanetkar, BPB Publications, 2003
■ Object Oriented Programming with C++, 8th Edition, E. Balaguruswamy, McGraw Hill
Publications, 2020
■ “C++: The Complete Reference”, 4th Edition, Herbert Schildt, McGraw Hill Education,
2017
■ “C++ Primer”, 5th Edition, Stanley B., Lippman, Josée Lajoie, Barbara E. Moo,
Pearson Education, 2012
■ “C++ Programming Language”, 4th Edition, Bjarne Stroustrup, Addison-Wesley,
2013
Programming Methodologies with C++
Pointers, Pointers with Arrays, Pointer to Members,
C++ Streams, C++ Stream Classes
Study material
Index
S. No. Content
1. Objectives
2. Pointers
3. Pointers with Arrays
4. Pointer to members
5. C++ Streams
6. C++ Stream Classes
7. Questions
8. References
1. Objectives
After studying this module the learner will be able to:
• Understand the use of Pointers
• Use Pointers with Arrays
• Know about various C++ Streams
• Implement C++ Stream Classes
2. Pointers
Pointers are variable that holds a memory address.
& indicates Address of
* indicates Value at address
Consider the following C++ code:
int i=3, *j,**k;
j=&i;
k=&j;
The variable i stores value 3, pointer j stores the address of i
and double pointer k stores the address of pointer j as shown
in the figure.
The system evaluates:
*k=*(&j)=6485
&j=3276
k=3276
**k=**(&j)=*(&i)=3
• A pointer can be incremented or decremented
• Any integer can be added or subtracted from a pointer
• One pointer can be subtracted from another
3. Pointers with Arrays
■ Pointers are useful to allocate arrays dynamically, i.e. we can decide the array size at
run time by using malloc() and calloc()
■ We can declare pointers to arrays as follows:
int *p,num[5];
p=num;
Example:
void main()
{ int num[50],*p,n,i, sum=0;
cout<<“\nEnter count:”;
cin>>n;
cout<<“\nEnter numbers:”;
for(i=0;i<n;i++)
cin>>num[i];
p=num;
for(i=0;i<n;i++)
{ if(*p%2==0) sum=sum+*p;
p++;
}
cout<<“\nSum of even numbers=“<<sum;
}
4. Pointers to Members
■ It is possible to take the address of a member of a class and assign it to a pointer.
class A
{ int m;
public: void show();
};
We can define a pointer to the member m as follows:
int A :: *p= &A :: m;
int *p=&m; //compilation error
■ m is not simply an int type data.
■ It has meaning only when it is associated with the class to which it belongs
■ The scope resolution operator (::) must be applied to both the pointer and the member
5. C++ Streams
Stream I/O Library Header Files
■ iostream -- contains basic information required for all stream I/O operations
■ iomanip -- contains information useful for performing formatted I/O with
parameterized stream manipulators
■ fstream -- contains information for performing file I/O operations
■ strstream -- contains information for performing in-memory I/O operations (i.e., into or
from strings in memory)
6. C++ Stream Classes
■ ios is the base class.
■ istream and ostream inherit from ios
■ ifstream inherits from istream (and ios)
■ ofstream inherits from ostream (and ios)
■ iostream inherits from istream and ostream (& ios)
■ fstream inherits from ifstream, iostream, and ofstream
C++ Stream I/O -- Stream Manipulators
■ C++ provides various stream manipulators that perform formatting tasks.
■ Stream manipulators are defined in <iomanip>
■ These manipulators provide capabilities for
– setting field widths
– setting precision
– setting and unsetting format flags
– flushing streams
– inserting a "newline" and flushing output stream
– skipping whitespace in input stream
setprecision ( )
■ Select output precision, i.e., number of significant digits to be printed.
■ Example:
cout << setprecision (2) ; // two significant digits
setw ( )
■ Specify the field width (Can be used on input or output, but only applies to next
insertion or extraction).
■ Example:
cout << setw (4) ; // field is four positions wide
I/O Stream Member Functions
.setf ( )
■ Allows the setting of an I/O stream format flag.
■ Examples:
// To show the + sign in front of positive numbers
cout.setf (ios::showpos) ;
// To output the number in hexadecimal
cout.setf (ios::hex, ios::basefield) ;
.precision ( ) ;
■ Select output precision, i.e., number of significant digits to be printed.
■ Example:
cout.precision (2) ; // two significant digits
.width ( ) ;
■ Specify field width. (Can be used on input or output, but only applies to next insertion
or extraction).
■ Example:
cout.width (4) ; // field is four positions wide
.eof ( ) ;
■ Tests for end-of-file condition.
■ Example:
cin.eof ( ) ; // true if eof encountered
.fail ( ) ;
■ Tests if a stream operation has failed.
■ Example:
cin.fail ( ) ; // true if a format error occurred
! cin; // same as above; true if format error
.clear ( ) ;
■ Normally used to restore a stream's state to "good" so that I/O may proceed or resume
on that stream.
■ Example:
cin.clear ( ) ; // allow I/O to resume
File I/O with C++
#include <fstream.h>
void main ( ) {
int a, b, c ;
ifstream fin ; //Create file input stream object
fin.open ( "my_input.dat") ; //Open input file
fin >> a >> b ; //Read two values from input file
c=a+b;
ofstream fout ; //Create file output stream object
fout.open ( "my_output.dat"); //Open output file
fout << c << endl ; //Write result to output file
fin.close ( ) ; //Close input file
fout.close ( ) ; //Close output file
}
7. Questions
Q.1) What is a pointer?
Q.2) How can pointers be used with arrays?
Q.3) What are C++ Streams?
Q.4) What are the various stream classes used in C++?
Q.5) Explain the various I/O stream member functions.
Q.6) How can you use streams for file handling?
8. References
■ Let us C++, 2nd Edition, Yashawant Kanetkar, BPB Publications, 2003
■ Object Oriented Programming with C++, 8th Edition, E. Balaguruswamy, McGraw Hill
Publications, 2020
■ “C++: The Complete Reference”, 4th Edition, Herbert Schildt, McGraw Hill Education,
2017
■ “C++ Primer”, 5th Edition, Stanley B., Lippman, Josée Lajoie, Barbara E. Moo,
Pearson Education, 2012
■ “C++ Programming Language”, 4th Edition, Bjarne Stroustrup, Addison-Wesley,
2013
Programming Methodologies with C++
Unformatted I/O Operation, Formatted I/O
Operation, Managing Output with Manipulators
Study material
Index
S. No. Content
1. Objectives
2. Unformatted I/O Operation
3. Formatted I/O Operation
4. Managing Output with Manipulators
5. Questions
6. References
1. Objectives
After studying this module the learner will be able to:
• Use functions for Unformatted I/O Operations
• Use functions for Formatted I/O Operations
• Manage Output with Manipulators
2. Unformatted I/O Operation
• Unformatted console input/output functions are used for performing input/output
operations at console and the resulting data is left unformatted and untransformed i.e.
it is left in its raw and original form.
• In C++, we can read the input entered by a user at console using an
object cin of istream class and through this object we can access the functions
of istream class, such as - get(char *), get(void) and getline().
• In C++, we can write the output at console using an object cout of ostream class and
through this object we can access the functions of ostream class, such as - put(), write().
• Some of the most important formatted console input/output functions are:
Functions Description
Reads a single character from the user at the console and assigns
get(char *) it to the char array in its argument, but needs an Enter key to be
pressed at the end.
Reads a single character from the user at the console, and returns
get()
it.
Reads a line of characters, entered by the user at the console
getline(char* arr, int size)
which ends with a newline character or until the size.
put(char ch) Writes a single character at the console.
write(char *arr, int num) Writes a number of characters in a char array to the console.
3. Formatted I/O Operation
Formatted console input/output functions are used for performing input/output operations at
console and the resulting data is formatted and transformed. Some of the most important
formatted console input/output functions are:
Functions Description
Using this function, we can specify the width of a value to be
width(int width)
displayed in the output at the console.
Using this function, we can fill the unused white spaces in a value
fill(char ch)
(to be printed at the console), with a character of our choice.
Using this function, we can set the flags, which allow us to display a
setf(arg1, arg2)
value in a particular format.
Using this function, we could clear the flag specified fixed by the
unsetf(char ch)
function setf().
Using this function, we can specify the number of
precision(int num_of_digts) digits(num_of_digits) to the right of decimal, to be printed in the
output.
In C++, we can read the input entered by a user at console using an object cin of istream class
and we can write the output at console using an object cout of ostream class. Through
the cin and cout objects, we can access the formatted I/O functions.
4. Managing output with Manipulators
The output can be formatted with the help of manipulators. Consider the following program:
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
void main ( )
{ clrscr();
int a, b, c = 8, d = 4 ;
float k ;
char name[30] ;
cout << "Enter your name" << endl ;
cin.getline (name, 30) ;
cout << "Enter two integers and a float " << endl ;
cin >> a >> b >> k ;
cout << "\nThank you, " << name << ", you entered"
<< endl << a << ", " << b << ", and " ;
cout.width (4) ;
cout.precision (2) ;
cout << k << endl ;
// Control the field and precision another way
cout <<"\nThank you, " << name << ", you entered"<< endl << a << ", " << b << ", and "
<< setw (c)
<< setprecision (d) << k << endl ;
getch();
}
Output:
Enter your name
Amar
Enter two integers and a float
4
4
6.88975
Thank you, Amar, you entered
4, 4, and 6.89
Thank you, Amar, you entered
4,4, and 6.8898
5. Questions
Q.1) How can you use functions for unformatted I/O Operations?
Q.2) How can you use functions for formatted I/O Operations?
Q.3) What are Manipulators?
Q.4) Write a C++ program to use manipulators for managing outputs on the console.
6. References
■ Let us C++, 2nd Edition, Yashawant Kanetkar, BPB Publications, 2003
■ Object Oriented Programming with C++, 8th Edition, E. Balaguruswamy, McGraw Hill
Publications, 2020
■ “C++: The Complete Reference”, 4th Edition, Herbert Schildt, McGraw Hill Education,
2017
■ “C++ Primer”, 5th Edition, Stanley B., Lippman, Josée Lajoie, Barbara E. Moo,
Pearson Education, 2012
■ “C++ Programming Language”, 4th Edition, Bjarne Stroustrup, Addison-Wesley,
2013
Programming Methodologies with C++
Exception Handling
Study material
Index
S. No. Content
1. Objectives
2. Exception
3. Exception Handling
4. Throwing Exceptions
5. Catching Exceptions
6. C++ Standard Exceptions
7. Defining New Exceptions
8. Questions
9. References
1. Objectives
After studying this module the learner will be able to:
• Define Exceptions
• Handle Exceptions in C++ programs
• Throw and Catch Exceptions
• Know about C++ Standard Exceptions
• Define new Exceptions
2. Exception
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.
3. Exception Handling
■ Find the problem (Hit the exception)
■ Inform that an error has occurred (Throw the exception)
■ Receive the error information (Catch the exception)
■ Take corrective actions (Handle the exception)
Exception Handling Mechanism is depicted below:
try block
Detects and throws an
exception
catch block
Exception Object
Catches and handles an
exception
Example:
#include <iostream.h>
void main()
{
int x = -1;
// Some code
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
catch (int x ) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
}
Output:
Before try
Inside try
Exception Caught
After catch (Will be executed)
4. 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);
}
5. 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>
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;
}
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!
6. 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 −
Here is the small description of each exception mentioned in the above hierarchy:
S.No Exception & Description
1
std::exception
An exception and parent class of all the standard C++ exceptions.
2
std::bad_alloc
This can be thrown by new.
3
std::bad_cast
This can be thrown by dynamic_cast.
4
std::bad_exception
This is useful device to handle unexpected exceptions in a C++
program.
5
std::bad_typeid
This can be thrown by typeid.
6
std::logic_error
An exception that theoretically can be detected by reading the code.
7
std::domain_error
This is an exception thrown when a mathematically invalid domain
is used.
8
std::invalid_argument
This is thrown due to invalid arguments.
9
std::length_error
This is thrown when a too big std::string is created.
10
std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
11
std::runtime_error
An exception that theoretically cannot be detected by reading the
code.
12
std::overflow_error
This is thrown if a mathematical overflow occurs.
13
std::range_error
This is occurred when you try to store a value which is out of range.
14
std::underflow_error
This is thrown if a mathematical underflow occurs.
7. Defining New Exceptions
You can define your own exceptions by inheriting and overriding exception class
functionality. Following is the example, which shows how you can use std::exception class to
implement your own exception in standard way −
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception {
const char * what () const throw () {
return "C++ Exception";
}
};
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}
This would produce the following result −
MyException caught
C++ Exception
Here, what() is a public method provided by exception class and it has been overridden by all
the child exception classes. This returns the cause of an exception.
8. Questions
Q.1) What are Exceptions?
Q.2) How is Exception handled in C++?
Q.3) What are throw and catch with respect to Exception Handling?
Q.4) Write a C++ program to use throw and catch to handle Exceptions.
Q.5) What are the various C++ Standard Exceptions?
9. References
■ Let us C++, 2nd Edition, Yashawant Kanetkar, BPB Publications, 2003
■ Object Oriented Programming with C++, 8th Edition, E. Balaguruswamy, McGraw Hill
Publications, 2020
■ “C++: The Complete Reference”, 4th Edition, Herbert Schildt, McGraw Hill Education,
2017