BCA-II oops C++ Uninnt 3,4,5
BCA-II oops C++ Uninnt 3,4,5
UNIT-III
Constructors and Destructors: Constructors, Parametric Constructors, Multiple Constructors in a class, constructors
with default arguments. Dynamic initialization of objects, copy constructors, dynamic constructors, destructors.
Operator Overloading & Type Conversions: Definition of Overloading, &Operator Overloading, rules for Overloading
Operators, Overloading Unary Operators, Binary Operators, Binary Operators using Friends.
Constructor
C++ is an object oriented programming (OOP) language which provides a special member function called constructor
for initializing an object when it is created. This is known as automatic initialization of objects. Constructor has the
same name as that of the class’s name and its main job is to initialize the value of the class. Constructors have no
return type, not even void.
Characteristics of Constructors
A constructor for a class is needed so that the compiler automatically initializes an object as soon as it is created. A
class constructor if defined is called whenever a program creates an object of that class. The constructor functions
have some special characteristics which are as follows:
• They should be declared in the public section.
• They are invoked directly when an object is created.
• They don’t have return type, not even void and hence can’t return any values.
• They can’t be inherited; through a derived class, can call the base class constructor.
• Constructors can’t be virtual.
• Constructor can be inside the class definition or outside the class definition.
• Constructor can’t be friend function.
• They make implicit calls to the operators new and delete when memory allocation is required.
A constructor is a special method that is created when the object is created or defined. This particular method holds
the same name as that of the object and it initializes the instance of the object whenever that object is created. The
constructor also usually holds the initializations of the different declared member variables of its object.
Constructor Overloading:-
When we use more than one constructor function defined in a class, then it is called constructor overloading or use of
multiple constructor in a class. It is used to increase the flexibility of a class by having more number of constructors for
a single class. Overloading constructors in C++ programming gives us more than one way to initialize objects in a
class.
Type of constructor
In object oriented programming (OOP’s), a constructor in a class is used to initialize the value of the object. It prepares
the new object for use by initializing its legal value. We will discuss main types of constructors, their features and
applications in the following section:
1. Default Constructor :- A constructor that has zero parameter list or in other sense, a constructor that accept no
arguments is called a zero argument constructor or default constructor. If default constructor is not defined in the
source code by the programmer, then the compiler defined the default constructor implicitly during compilation.
If the default constructor is defined explicitly in the program by the programmer, then the compiler will not define
the constructor implicitly, but it calls the constructor implicitly.
2. Parameterized Constructor:-We can write a constructor in C++ which can accept parameters for its invocation.
Such constructor that can take the arguments are called parameterized constructor. In other words; “Declaring a
constructor with arguments hides the default constructor”.
3. Copy Constructor:- A copy constructor is used to declare and initialize an object from another object. Thus the
process of initializing through a copy constructor is known as copy initialization. The copy constructors are used in
the following situations
• The initialization of an object by another object of the same class.
• Return of objects as a function value.
The syntax of copy constructor is: class_name(class_name &ptr)
Example of Constructor
#include <iostream.h>
class Emp
{
private:
Operator Overloading
Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in
C++ without changing its original meaning. C++ has the ability to provide the operators with a special meaning for a
data type, this ability is known as operator overloading. C++ provides a special function to change the current
functionality of some operators within its class which is often called as operator overloading.
Syntax:-
returnType operator symbol (arguments)
{
... .. ...
}
Types of Operator Overloading in C++
• Overloading Unary Operator.
• Overloading Binary Operator.
Example:
#include <iostream.h>
class Complex
{
private:
int real;
int img;
public:
Complex (int r, int i )
{
real = r;
img = i;
}
void Disp()
{
cout << real << "+i" << img;
}
friend Complex operator + (Complex c1, Complex c2);
};
Complex operator + (Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;
return temp;
Type conversion :
Type Conversions In a mixed expression constants and variables are of different data types. The assignment
operations causes automatic type conversion between the operand as per certain rules. The type of data to the right
of an assignment operator is automatically converted to the data type of variable on the left at the compiler time.
example –
int x=30;
float y;
y=x; // y==30.000000.
There are three types of situations that arise where data conversion are between incompatible types.
1. Conversion from built in type to class type.
2. Conversion from class type to built in type.
3. Conversion from one class type to another.
Type Casting: In typing casting, a data type is converted into another data type by the programmer using the casting
operator during the program design. In typing casting, the destination data type may be smaller than the source data
type when converting the data type to another data type, that’s why it is also called narrowing conversion and may
lead to data loss
float x=3.14;
byte y;
y=(byte)x; // we are converting float(source) data type into byte(target) data type.
Inheritance:
C++ strongly supports the concept of reusability. The C++ classes can be used again in several ways. Once a class
has been written and tested, it can be adopted by another programmers. This is basically created by defining the new
classes, reusing the properties of existing ones. The mechanism of deriving a new class from an old one is called
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class being defined "is" also
an object of inherited class. The old class is called 'BASE' class and the new one is called 'DERIEVED' class. It is a
feature that enables a class to acquire properties and characteristics of another class.
2. Multiple Inheritance
The inheritance in which a class can inherit or derive the characteristics of multiple classes, or a derived class can
have over one base class, is known as Multiple Inheritance. It specifies access specifiers separately for all the base
classes at the time of inheritance. The derived class can derive the joint features of all these classes and the data
members of all the base classes are accessed by the derived or child class according to the access specifiers.
4. Hierarchical Inheritance
The inheritance in which a single base class inherits multiple derived classes is known as the Hierarchical Inheritance.
This inheritance has a tree-like structure since every class acts as a base class for one or more child classes. The
visibility mode for each derived class is specified separately during the inheritance and it accesses the data members
accordingly.
Syntax
class class_A
{
// class definition
};
class class_B: visibility_mode class_A
{
// class definition
};
5. Hybrid Inheritance
Hybrid Inheritance, as the name suggests, is the combination of two or over two types of inheritances. For example,
the classes in a program are in such an arrangement that they show both single inheritance and hierarchical
inheritance at the same time. Such an arrangement is known as the Hybrid Inheritance. This is arguably the most
complex inheritance among all the types of inheritance in C++. The data members of the base class will be accessed
according to the specified visibility mode.
Abstract Classes
In programming, an abstract class in C++ has at least one pure virtual function by definition. In other words,
a function that has no definition. The abstract class's descendants must define the pure virtual function; otherwise, the
subclass would become an abstract class in its own right. Abstract classes are used to express broad concepts from
which more concrete classes can be derived. An abstract class type object cannot be created. To abstract class types,
however, you can use pointers and references. We Declare at least one pure virtual member feature when creating an
abstract class. The pure specifier (= 0) syntax is used to declare a virtual function.
Syntax:
Class classname //abstract class
{
//data members
public:
//pure virtual function /* Other members */
};
Nesting Of Class.
A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing
class and has the same access rights as the other members. However, the member functions of the enclosing class
have no special access to the members of a nested class.
#include<iostream.h>
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
void main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
}
Pointer
A pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare
a pointer before you can work with it. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer variable.
The asterisk you used to declare a pointer is the same asterisk that you use for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
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.
This pointer
In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of
this keyword in C++.
• It can be used to pass current object as a parameter to another method.
• It can be used to refer current class instance variable.
• It can be used to declare indexers.
C++ this Pointer Example
#include <iostream.h>
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
void main(void) {
Employee e1 =Employee(101, "Kshitiz", 89000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
}
Pointer to derived class
In object-oriented programming, Pointer can be used for objects of base classes as well as objects of derived classes.
A pointer to a derived class refers to a pointer that points to an object of a derived class, which is a subclass that
inherits from a base class. The concept is based on inheritance, where a derived class inherits the properties and
behaviours (data members and member functions) of the base class.
by a pointer to a derived class, we can use it to access both the member functions and data members of the base
class and the additional ones defined in the derived class. This is one of the fundamental features of polymorphism,
as you can treat objects of the derived class as objects of the base class, allowing for code reusability and flexibility.
2. catch in C++
3. throw in C++
An exception in C++ can be thrown using the throw keyword. When a program encounters a throw statement, then it
immediately terminates the current function and starts finding a matching catch block to handle the thrown exception.
Note: Multiple catch statements can be used to catch different type of exceptions thrown by try block.
The try and catch keywords come in pairs: We use the try block to test some code and If the code throws an exception
we will handle it in our catch block.
Grouping of Error Types: In C++, both basic types and objects can be thrown as exceptions. We can create a
hierarchy of exception objects, group exceptions in namespaces or classes, and categorize them according to their
types.
// C++ program to demonstrate the use of try,catch and throw in exception handling.
#include <iostream.h>
#include <stdexcept.h>
void main()
{
// try block
try {
int numerator = 10;
int denominator = 0;
int res;
// check if denominator is 0 then throw runtime error.
if (denominator == 0) {
throw runtime_error( "Division by zero not allowed!");
}
// calculate result if no exception occurs
res = numerator / denominator;
//[printing result after division
cout << "Result after division: " << res << endl;
}
// catch block to catch the thrown exception
catch (const exception& e) {
// print the exception
cout << "Exception " << e.what() << endl;
}
}
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.
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.
File handling in C++ is a mechanism to store the output of a program in a file and help perform various operations on
it. Files help store these data permanently on a storage device.
file handling is further divided into sub-topics:
• Create a file
• Open a file
• Read from a file
• Write to a file
• Close a file
fstream library
Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file
handling method. In C++, fstream library is used to handle files, and it is dealt with the help of three classes known as
ofstream, ifstream and fstream.
1. ofstream:This class helps create and write the data to the file obtained from the program’s output. It is also known
as the input stream.
2. ifstream:We use this class to read data from files and also known as the input stream.
3. fstream:This class is the combination of both ofstream and ifstream. It provides the capability of creating, writing
and reading a file.
To access the following classes, we must include the fstream as a header file like how we declare iostream in the
header.
#include <fstream.h>
#include <iostream.h>
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("myfile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore(); // clear buffer and again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("myfile.dat");
cout << "Reading from the file" << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;