Oop Java Mu Notes
Oop Java Mu Notes
CHAPTER – 01
APPROACH
Following Table presents the summary of main features of these programming paradigms.
Introduction to OOPs
Functions that operate on the data of an object are tied together in the data structure.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through functions.
New data and functions can be easily added whenever necessary.
Follow bottom-up approach in program design.
There are two different approaches to write a program, i.e., Procedure Oriented Programming
and Object Oriented Programming. Basic aim of these methods is nothing but to make
programming efficient. We can write the program using any of the way but there are notable
differences between both approaches.
1) As OOP is closer to the real world phenomena, hence, it is easier to map real world problems
onto a solution in OOP.
2) The objects in OOP have the state and behaviour that is similar to the real world objects.
3) It is more suitable for large projects.
4) The projects executed using OOP techniques are more reliable.
5) It provides the bases for increased testability (automated testing) and hence higher quality.
6) Abstraction techniques are used to hide the unnecessary details and focus is only on the
relevant part of the problem and solution.
7) Encapsulation helps in concentrating the structure as well as the behaviour of various objects
in OOP in a single enclosure.
8) The enclosure is also used to hide the information and to allow strictly controlled access to the
structure as well as the behaviour of the objects.
9) OOP divides the problems into collection of objects to provide services for solving a
particular problem.
10) Object oriented systems are easier to upgrade/modify.
11) The concepts like inheritance and polymorphism provide the extensibility of the OOP
languages.
12) The concepts of OOP also enhance the reusability of the code written.
13) Software complexity can be better managed.
14) The use of the concept of message passing for communication among the objects makes the
interface description with external system much simpler.
15) The maintainability of the programs or the software is increased manifold. If designed
correctly, any tier of the application can be replaced by another provided the replaced tier
implements the correct interface(s). The application will still work properly.
1.7 ADVANTAGES OF OOPs
____________________________________________________________________________________________
Object concept helps to translate our thoughts to a program. It provides a way of solving a
problem in the same way as a human being perceives a real world problem and finds out the
solution. It is possible to construct large reusable components using object-oriented techniques.
Development of reusable components is rapidly growing in commercial software industries. If
there is complexity in software development, object-oriented programming is the best
paradigm to solve the problem. The following areas make the use of OOP:
1. Image Processing
2. Pattern Recognition
3. Computer Assisted Concurrent Engineering
4. Computer Aided Design and Manufacturing
5. Computer Aided Teaching
6. Intelligent Systems
7. Database Management Systems
8. Web-based Applications
9. Distributed Computing and Applications
10. Component-based Applications
11. Business Process Re-engineering
12. Enterprise Resource Planning
13. Data security and management
14. Mobile Computing
15. Data Warehouse and Data Mining
16. Parallel Computing
Q1. Why does hardware not provide flexibility of operations to the user ?
Q5. What is the difference between object-oriented and object-based programming languages?
CHAPTER – 02
Principles of OOPS
Chapter Structure :
Simula was the first programming language developed in the mid-1960s to support the object-
oriented programming paradigm followed by Smalltalk in the mid-1970s that is known to be the
first ‘pure’ object-oriented language. Eiffel, Java, C++, Object Pascal, Visual Basic, C# etc are
the other OOP languages that came into existence later on, all having different complexities of
syntax and dynamic semantics.
The main motive of the developers of programming languages over the years has always been to
create such programming languages that are close to human (i.e. natural) languages. The way we
perceive and interact with the things in our day-to-day lives, the representation of programming
constructs should closely match the same. Hence came into existence the concept of ‘objects’
and ‘object-oriented programming paradigm’. Every object has certain defining properties which
distinguish it not only from different types of other objects but from the similar types of objects
too. If we take an example of an object like a ball pen, its defining property may be the colour in
which it can write, length, shape, unique manufacturing code etc. Some of these properties not
only distinguish the ball pen object from the tooth brush object but also distinguish individual
ball pens objects. It must be understood clearly that no two objects in the physical world, even of
same type, are identical since no two objects can have the value of all its defining properties
same. Likewise, every object has certain functions associated with it and all similar types of
objects are supposed to support these. Although, Some of these functions can be the same as
associated with different types of objects. In case of a ball pen, one of the functions associated
with each type of ball pen object, is to write and another associated function is the provision to
hold it in hands conveniently. All the ball pen objects support both these functions. Incidentally,
all the tooth brush objects also support the function of holding them in the hands conveniently
but, in addition, support other functions like brushing the teeth too.
This concept of objects borrowed from the real world has been the basis of the object-oriented
programming (OOP) paradigm and this paradigm is a direct consequence of an effort to have a
programming language closely matching the human behaviour. This OOP paradigm is all about
creating program(s) dealing with objects where these objects interact with one another to achieve
the overall objectives of the program. Every object in the programs has certain defining
properties called attributes (or instance variables) possessing supporting values for each of the
attributes and some associated functions (normally called methods or operations). As in the real
world objects, no two objects in a program can have the same values of all the attributes.
At times, instead of dealing with individual objects, it is convenient to talk collectively about a
group of similar objects where all the objects of this group will have the same set of attributes
and methods. In the object-oriented programming paradigm parlance, this collection of objects
corresponding to a particular group is known as a class. All programs under this paradigm
contain a description of the structure (corresponding to attributes) and behaviour (corresponding
to methods) of so called classes. In a program, various objects are created from these classes.
The process of creation of an object from a class is called ‘instantiation’ and the object created is
known as an instance of the class. Every object created will have a ‘state’ associated with the
description of the structure in the class from which it has been instantiated. The state of an object
is defined by the set of values assigned to its corresponding attributes (and stored in the memory)
of the object. Therefore, we can say that a class is used to represent a set of objects having same
structure and behaviour. So, how do we define a class? A class is defined to be a template or a
prototype so that a collection of attributes and methods can be described within it and this
definition can be used for creating different objects within a program. It is this concept of
encapsulating the data and methods within the objects that provides the programmers with
flexibility within the OOP paradigm because an object can be extended or modified without
making changes to its external interface or other classes/objects in the program. Various classes
may exhibit features like inheritance and polymorphism of methods.
When a program is executed, various objects are created with their corresponding states and
these objects interact with one another by exchanging messages, the messages thereby causing
the modification of their states. Modification in the state of an object is said to have occurred
when the values of one or more of its attributes (instance variables) change due to the interaction.
All the objects created are made to exhibit a behaviour through their corresponding methods such
that the program produces the desired results once its execution is over. A program in this
paradigm therefore, becomes a collection of cooperating and interacting objects instead of just a
list of objects. For the sake of an example, a Maruti Wagon-R could be an object. It would have a
state depend upon whether its engine is running or not. Also it would have a behaviour, like
starting ignition of its engine or stopping the ignition of its engine and this behaviour is
responsible for changing its state from ‘engine is not running’ to ‘engine is running’ or from
‘engine is running’ to ‘engine is not running’. In a different example, we can take object ABC
representing a student having a state defined by its attribute named RESULT. A part of the
behaviour of this object could be reflected through ‘compute result’. If this student has not
appeared in the examination yet, the state of this object defined by the attribute RESULT may be
NOT DECLARED. But once this student has appeared in the examination and the marks
obtained by this student are available, the behaviour of this object changes the state of the object
ABC by using the method ‘compute result’ from NOT DECLARED to either FAIL or PASS
with percentage of marks.
Object
Classes
Polymorphism
Inheritance
Reusability
Data abstraction and encapsulation
Class
A group of objects that share common properties for data part and some program part are
collectively called as class. In C ++ a class is a new data type that contains member variables and
member functions that operate on the variables.
The most remarkable feature of C + + is a class. The class binds together data and methods
which work on data. The class is an abstract data type (ADI) so creation of class simply creates
a template. The general syntax of creating a class in C++ is given below:
The class is a keyword. Following this keyword class, class_name represents name of the
class. The class name must obey rules of writing identifier as class_name is nothing but an
identifier. The class is opened by opening brace} and closed by closing brace}. The class
definition/declaration must end with semicolon. Inside the class we define the data members
and member functions. They may be defined either public, private or jn protected mode. There
are three different types of mode :
1. public
2. private
3. protected.
Object
Objects are the basic run time entities in an Object Oriented System. They may represent a
person, a bank account, a table of data or any item that the program has to handle. They may also
represent user-defined data such as vector, time, and lists. When a program is executed, the
objects interact by sending messages to one another. Creating objects is similar to declaring
variables.
Syntax:
For Example:
Student s1;
Where Student is a class name and s1 is its object.
Polymorphism
Poly means many. Morphism means forms. Polymorphism feature enables classes to provide
different implementation of methods having the same name.
There are two types of polymorphism:
1. Compile time (Overloading)
2. Run time (Overriding)
Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of
another class. It supports the concept of hierarchical classification. The existing class is called as
base class and a new class which is created on the basis of base class is called as derived class.
There are 5 different types of inheritance, i.e.:
Single level
Multilevel
Multiple
Hierarchical
Hybrid
Reusability
The wrapping up of data and functions into a single unit is known as encapsulation.
Data encapsulation is the most striking feature of a class.
Abstraction refers to the act of representing essential features without including the
background details or explanations.
Encapsulation is the hiding of information in order to ensure that data structures and
operators are used as intended and to make the usage model more obvious to the
developer.
C++ provides the ability to define classes and functions as its primary encapsulation
mechanisms.
Dynamic Binding
Message Passing
In C++ objects communicate each other by passing messages to each other. A message contains
the name of the member function and arguments to pass. In message passing shown below :
object. method (parameters);
Message passing here means object calling the method and passing parameters. Message
passing is nothing but the calling the method of the class and sending parameters. The method
is turn executes in response to a message.
CHAPTER – 03
3.0.2 Tokens:
3.0.3 Identifiers
3.0.4 Keywords
3.0.8 VARIABLES
Digits 0-9
A character that is used to produce blank space when printed in C++ is called white space character.
These are spaces, tabs, new-lines, and comments.
3.0.2 Tokens:
______________________________________________________________________________________________
A token is a group of characters that logically combine together. The programmer can write a
program by using tokens. C++ uses the following types of tokens:
Keywords
Identifiers
Literals
Punctuators
Operators
3.0.3 Identifiers
______________________________________________________________________________________________
A symbolic name is generally known as an identifier. Valid identifiers are a sequence of one or more
letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be
part of an identifier. Only letters, digits and single underscore characters are valid. In addition,
variable identifiers always have to begin with a letter. In no case can they begin with a digit. Another
rule for declaring identifiers is that they cannot match any keyword of the C++ programming
language. The rules for the formation of identifiers can be summarised as:
A symbolic name is generally known as an identifier. Valid identifiers are a sequence of one or more
letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be
part of an identifier. Only letters, digits and single underscore characters are valid. In addition,
variable identifiers always have to begin with a letter. In no case can they begin with a digit. Another
rule for declaring identifiers is that they cannot match any keyword of the C++ programming
language. The rules for the formation of identifiers can be summarised as:
3.0.4 Keywords
______________________________________________________________________________________________
There are some reserved words in C++ which have predefined meaning to complier called keywords.
These are also known as reserved words and are always written or typed in lower cases. There are
following keywords in C++ object oriented language:
List of Keywords:
1)
#include <iostream.h> // Section: 1- The include Directive
int main () // Section: 3 - Main function definition
{ // Section: 4 - Declaration of an object
cout << "Hello World!";
return 0;
}
2)
#include <iostream.h>
# include<conio.h>
main()
{
char name [15];
clrscr();
cout << "Enter your name:”;
cin >> name;
cout<<”Your name is: “ <<name;
return0;
}
3)
#include <iostream.h>
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
C, must occur at the top of the function block and it must be declared
before any executable statement. In C++ variables can be declared anywhere in the program.
no such
facility in C language.
1. Built-in Type
(a) class
(b) struct
(c) union
(d) enumeration
(a) array
(b) function
(c) pointer
(d) reference
3.0.8 VARIABLES
______________________________________________________________________________________________
A variable is a named location in memory that is used to hold a value that can be modified
in the program by the instruction. All variables must be declared before they can be used. They
must be declared in the beginning of the function or block (except the global variables). The
general form of variable declaration is :
Example :
int a;
float b,c;
char p,q;
Here a is a variable of type int, b and c are variable of type float, and p, q are variables
of type char, int, float and char are data types used in C. The rule for writing variables are same
as for writing identifiers as a variables is nothing but an identifier.
C++ allows you to declare variables anywhere in the program. That is unlike C it is not
necessary to declare all the variables in the beginning of the program. You can declare wherever
you want it to be declares i.e., right on the place where you want to use it. An advantage of
this is that sometimes lots of variables are declared in the advance in the beginning of the
program and many of them are unreferenced. Declaring variables at the place where they are
actually required is handy. You do not need to declare all the variables earlier prior to their use.
On the other hand, it is burdensome to look for all the variable declared in the program as
variable declaration will be scattered everywhere in the whole program.
C++ also allows you to initialize variable dynamically at the place of use. That is you can
write anywhere in the program like this.
int x = 23;
float sal = 2345;
char name[ ] = “Hari”;
This is known as “Dynamic Initialization” of the variables.
The above declaration means that Pi is a constant of float types having a value: 3.1415.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators
one by one.
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are
as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then −
Assignment Operators
There are following assignment operators supported by C++ language −
Misc Operators
The following table lists some other operators that C++ supports.
1
sizeof
sizeof operator returns the size of a variable. For example,
sizeof(a), where „a‟ is integer, and will return 4.
2
Condition ? X : Y
Conditional operator (?). If Condition is true then it
returns value of X otherwise returns value of Y.
3
,
Comma operator causes a sequence of operations to be
performed. The value of the entire comma expression is
the value of the last expression of the comma-separated
list.
4
. (dot) and -> (arrow)
Member operators are used to reference individual
members of classes, structures, and unions.
5
Cast
Casting operators convert one data type to another. For
example, int(2.2000) would return 2.
6
&
Pointer operator & returns the address of a variable. For
example &a; will give actual address of the variable.
7
*
Pointer operator * is pointer to a variable. For example
*var; will pointer to a variable var.
In this type of statement, the execution of a block depends on the next condition. If the condition
evaluates to true, then one set of statement is executed, otherwise another set of statements is
executed. C++ provides following types of selection statements: If; If-else; Nested if; Switch
conditional
a) if statement:
If (expression)
{
(Body of if)
Statements;
}
Where, expression is the condition that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues right after this
conditional structure.
# include <iostream.h>
main()
{ int a, b;
a=10;
b=20;
if (a<b)
cout <<”a is less than b”;
}
b) if-else statement:
If (expression)
{
(Body of if)
Statements 1;
}
else
{
(Body of else}
Statement 2
}
# include <iostream.h>
main()
{ int a, b;
a=10;
b=20;
if (a<b)
cout <<”a is less than b”;
}
else
{
cout<< “b is less than a”
}
c) Switch statement:
Switch statement is used for multiple branch selection. The syntax of switch statement is
switch (expression)
{
case exp 1:
First case body;
Break;
case exp 2:
Second case body;
Break;
case exp 3:
Third case body;
Break;
default:
default case body;
}
# include <iostream.h>
# include <conio.h>
int main()
{
clrscr();
int d_o_w;
cout <<”Enter number of week‟s day (1-7)”;
cin>>d_o_w;
switch(d_o_w)
{
case 1: cout<<”/n Sunday”;
break;
case 2: cout<<”/n Monday”;
break;
case 3: cout<<”/n Tuesday”;
break;
case 4: cout<<”/n Wednesday”;
break;
case 5: cout<<”/n Thursday”;
break;
case 6: cout<<”/n Friday”;
break;
case 7: cout<<”/n Saturday”;
break;
default: cout<<”/n Wrong number of day”;
}
return 0;
}
Output:
Enter number of week‟s dat (1-7):
7
Saturday
This loop is specially designed to perform a repetitive action with a counter which is initialized and
increased on each iteration
#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "****!\n";
return 0;
}
#include <iostream.h>
using namespace std;
int main ()
{
unsigned long n;
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
}
while (n != 0);
return 0;
}
break statement
continue statement
goto statement and
exit statement
Output:
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
Output:
Enter the number: 2
The number is: 2
Enter the number: 3
The number is: 3
Enter the number: 9
The number is greater than or equal to 9
3.1 C++ Classes and Objects
______________________________________________________________________________________________
The main purpose of C++ programming is to add object orientation to the C programming language and
classes are the central feature of C++ that supports object-oriented programming and are often called user-
defined types.
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package. The data and functions within a class are called members of the
class.
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follows it. A public
member can be accessed from outside the class anywhere within the scope of the class object. You can also
specify the members of a class as private or protected which we will discuss in a sub-section.
int main()
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed directly using direct member
access operator (.). We will learn how private and protected members can be accessed.
A class member can be defined as public, private or protected. By default members would
be assumed as private.
A class constructor is a special function in a class that is called when a new object of the class
is created. A destructor is also a special function which is called when created object is deleted.
Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an object
of the same class, which has been created previously.
Friend Functions
A friend function is permitted full access to private and protected members of a class.
Inline Functions
With an inline function, the compiler tries to expand the code in the body of the function in
place of a call to the function.
this Pointer
Every object has a special pointer this which points to the object itself.
A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class
is really just a structure with functions in it.
Both data members and function members of a class can be declared as static.
Syntax:
ClassName ObjectName;
The data members and member functions of class can be accessed using the dot(„.‟) operator with
the object. For example if the name of object is obj and you want to access the member function
with the name printName() then you will have to write obj.printName() .
private yes no
protected yes no
The syntax of a member function definition changes depending on whether it is defined inside or outside the
class declaration/definition. However, irrespective of the location of their definition, the member function
must perform the same operation. Thus, the code inside the function body would be identical in both the
cases. The compiler treats these two definitions in a different manner. Let us see, how we can define the
member function inside the class definition.
The syntax for specifying a member function declaration is similar to a normal function definition except that
is enclosed within the body of a class. Foe example, we could define the class as follows:
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<"\n Minimum value is ="<<min<<endl;
}
};
if you look at the above declaration of class number you can observe that the member function get_data() and
maiximun() are declared, but they are not defined. The only member function which is defined in the class
body is minimum(). When a function is defined inside a class, it is treated as a inline function. Thus, member
function minimum is a inline function. Generally, only small functions are defined inside the class.
Now let us see how we can define the function outside the class body. Member functions that are declared
inside a class have to be defined outside the class. Their definition is very much like the normal function. Can
you tell how does a compiler know to which class outside defined function belong? Yes, there should be a
mechanism of binding the functions to the class to which they belong. This is done by the scope resolution
operator (::). It acts as an identity-label. This label tells the compiler which class the function belongs to. The
common syntax for member function definition outside the class is as follows:
return_type class_name :: function_name(argument declaration)
{
functionbody
}
The scope resolution :: tells the compiler that the function_name belongs to the class class_name.
Let us again consider the class Number.
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration.
.
.
};
void Number :: get_data(void)
{
cout<< "\n Enter the value of fist number(x):"<<endl;
cin>>x;
cout<< "\n Enter the value of second number(y):"<<endl;
cin>>y;
cout<< "\n Enter the value of third number(z):"<<endl;
cin>>z;
}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<"\n Maximun value is ="<<max<<endl;
}
if you look at the above declaration of class Number, you can easily see that the member function get_data()
and maiximun() are declared in the class. Thus, it is necessary that you have to define this function. You can
also observe in the above snapshot of C++ program identity label (::) which are used in void Number ::
get_data(void) and void Number ::maximum(void) tell the compiler the functionget_data() and maximum()
belong to the class Number.
Now, let us see the complete C++ program to find out the minimum and maximum of three given integer
numbers:
#include<iostream.h>
class Number
{
int x, y, z;
public:
void get_data(void); //declaration
void maximum(void); //declaration
void minimum(void) //definition
{
int min;
min=x;
if (min>y)
min=y;
if (min>z)
min=z;
cout<<"\n Minimum value is ="<<min<<endl;
}
};
void Number :: get_data(void)
{
cout<< "\n Enter the value of fist number(x):"<<endl;
cin>>x;
cout<< "\n Enter the value of second number(y):"<<endl;
cin>>y;
cout<< "\n Enter the value of third number(z):"<<endl;
cin>>z;
}
void Number :: maximum(void)
{
int max;
max=x;
if (max<y)
max=y;
if (max<z)
max=z;
cout<<"\n Maximun value is ="<<max<<endl;
}
void main()
{
Number num;
num.get_data();
num.minimum();
num.maximum();
}
output:
Enter the value of the first number (x):
10
Enter the value of the second number (y):
20
Enter the value of the third number (z):
5
Minimum value is=5
Maximum value is=20
To pass an object as an argument we write the object name as the argument while calling the function the
same way we do it for other variables.
Syntax:
function_name(object_name);
Example: In this Example there is a class which has an integer variable „a‟ and a function „add‟ which takes
an object as argument. The function is called by one object and takes another as an argument. Inside the
function, the integer value of the argument object is added to that on which the „add‟ function is called. In this
method, we can pass objects as an argument and alter them.
// of objects to a function
#include<iostream.h>
class Example {
public:
int a;
// This function will take
// an object as an argument
void add(Example E)
{
a = a + E.a;
}
};
// Driver Code
int main()
{
// Create objects
Example E1, E2;
// Values are initialized for both objects
E1.a = 50;
E2.a = 100;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a << "\n\n";
// Passing object as an argument
// to function add()
E2.add(E1);
// Changed values after passing
// object as argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";
return 0;
}
Output:
Initial Values
Value of object 1: 50
& object 2: 100
New values
Value of object 1: 50
& object 2: 150
Example: In the above example we can see that the add function does not return any value since its return-
type is void. In the following program the add function returns an object of type „Example'(i.e., class name)
whose value is stored in E3.
In this example, we can see both the things that are how we can pass the objects as well as return them. When
the object E3 calls the add function it passes the other two objects namely E1 & E2 as arguments. Inside the
function, another object is declared which calculates the sum of all the three variables and returns it to E3.
This code and the above code is almost the same, the only difference is that this time the add function returns
an object whose value is stored in another object of the same class „Example‟ E3. Here the value of E1 is
displayed by object1, the value of E2 by object2 and value of E3 by object3.
Output:
Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0
New values
Value of object 1: 50,
object 2: 100,
object 3: 200
3.12 FRIEND FUNCTION
______________________________________________________________________________________________
As we have discussed that the private members cannot be accessed from outside the class. It implies that a
non-member function cannot have an access to the private data of a class. Let us suppose, we want a function
operate on objects of two different classes. In such situations, C++ provides the friend function which is used
to access the private members of a class. Friend function is not a member of any class. So, it is defined
without scope resolution operator. The syntax of declaring friend function is given below:
class class_name
{
…
…
public:
…
…
friend return type function_name(arguments);
}
Let us consider the complete C++ program to find out sum of n given numbers to understand the concept of
friend function
#include<iostream.h>
#define MAX_SIZE 100
class Sum
{
int num[MAX_SIZE];
int n;
public:
void get_number(void);
friend int add(void);
};
void Sum :: get_number(void)
{
cout<< "\n Enter the total number(n):"<<endl;
cin>>n;
cout<< "\n Enter the number:"<<endl;
for (int i=0;i<n; i++)
cin>>num[i];
}
int add(void)
{
Sum s;
int temp=0;
s.get_number();
for (int i=0;i<s.n; i++)
temp+=s.num[i];
return temp;
}
void main()
{
int res;
res=add();
cout<<"The sum of n value is="<<res<<endl;
}
If you look at the above program, you can easily see that the function add is declared as a friend function of
class Sum. The add function accesses the private data, adds the numbers of array and returns value to the main
function where it is called upon. Furthermore, you can also see that friend function add() is defined without
scope resolution operator(::), because it does not belong to a class.
Now, let us consider a situation in which we want to operate on objects of two different classes. In such a
situation, friend functions can be used to bridge the two classes
#include<iostream.h>
class Two; //forward declaration like function prototype
class One
{
int a;
public:
void get_a(void);
friend int min(One, Two);
};
class Two
{
int b;
public:
void get_b(void);
friend int min(One, Two);
};
void One :: get_a(void)
{
cout<<"Enter the value of a:"<<endl;
cin>>a;
}
void Two :: get_b(void)
{
cout<<"Enter the value of b:"<<endl;
cin>>b;
}
int min (One o, Two t)
{
if(o.a<t.b)
return o.a;
else
return t.b;
}
void main()
{
One one;
Two two;
int minvalue;
one.get_a();
two.get_b();
minvalue=min(one,two);
cout<<"Minimum="<<minvalue<<endl;
}
You can observe that the above program contains two classes named one and two. The function min() is
declared in the both the classes with the keyword friend. An object of each class has been passed as an
argument to the function min (). Being a friend function, it can access the private members of both classes
through these arguments.
(i) A friend function is not in the scope of the class to which it has been declared as friend.
(ii) A friend function cannot be called using the object of that class. It can be invoked like a normal function
without the use of any object.
(iii) Unlike member functions, it can not access the members directly. However, it can use the object and dot
membership operator with each member name to access both private and public members.
(iv) It can be declared either in the public or the private part of a class without affecting its meaning.
(v) Generally, it has got objects as arguments.
#include <iostream.h>
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Box *ptrBox; // Declare pointer to a class.
// Save the address of first object
ptrBox = &Box1;
return 0;
}
Output :
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
Array and pointers are closely related to each other. In C++, the name of an array is considered às a pointer,
i.e., the name of an array contains the address of an element. C++ considers the array name as the address of
the first element. For example, if we create an array, i.e., marks which hold the 20 values of integer type, then
marks will contain the address of first element, i.e., marks[0]. Therefore, we can say that array name (marks)
is a pointer which is holding the address of the first element of an array.
1. #include <iostream.h>
2. int main()
3. {
4. int *ptr; // integer pointer declaration
5. int marks[10]; // marks array declaration
6. std::cout << "Enter the elements of an array :" << std::endl;
7. for(int i=0;i<10;i++)
8. {
9. cin>>marks[i];
10. }
11. ptr=marks; // both marks and ptr pointing to the same element..
12. std::cout << "The value of *ptr is :" <<*ptr<< std::endl;
13. std::cout << "The value of *marks is :" <<*marks<<std::endl;
14. }
In the above code, we declare an integer pointer and an array of integer type. We assign the address of marks
to the ptr by using the statement ptr=marks; it means that both the variables 'marks' and 'ptr' point to the same
element, i.e., marks[0]. When we try to print the values of *ptr and *marks, then it comes out to be same.
Hence, it is proved that the array name stores the address of the first element of an array.
Output :
Array of Pointers
An array of pointers is an array that consists of variables of pointer type, which means that the variable is a
pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer pointers;
then its declaration would look like:
In the above declaration, we declare an array of pointer named as ptr, and it allocates 5 integer pointers in
memory.
The element of an array of a pointer can also be initialized by assigning the address of some other element.
Let's observe this case through an example.
In the above code, we are assigning the address of 'a' variable to the third element of an array 'ptr'.
1. *ptr[2];
1. #include <iostream.h>
2. int main()
3. {
4. int ptr1[5]; // integer array declaration
5. int *ptr2[5]; // integer array of pointer declaration
6. std::cout << "Enter five numbers :" << std::endl;
7. for(int i=0;i<5;i++)
8. {
9. std::cin >> ptr1[i];
10. }
11. for(int i=0;i<5;i++)
12. {
13. ptr2[i]=&ptr1[i];
14. }
15. // printing the values of ptr1 array
16. std::cout << "The values are" << std::endl;
17. for(int i=0;i<5;i++)
18. {
19. std::cout << *ptr2[i] << std::endl;
20. }
21. }
In the above code, we declare an array of integer type and an array of integer pointers. We have defined the
'for' loop, which iterates through the elements of an array 'ptr1', and on each iteration, the address of element
of ptr1 at index 'i' gets stored in the ptr2 at index 'i'.
Output :
Till now, we have learnt the array of pointers to an integer. Now, we will see how to create the array of
pointers to strings.
An array of pointer to strings is an array of character pointers that holds the address of the first character of a
string or we can say the base address of a string.
The following are the differences between an array of pointers to string and two-dimensional array of
characters:
o An array of pointers to string is more efficient than the two-dimensional array of characters in case of memory
consumption because an array of pointer to strings consumes less memory than the two-dimensional array of
characters to store the strings.
o In an array of pointers, the manipulation of strings is comparatively easier than in the case of 2d array. We can
also easily change the position of the strings by using the pointers.
In the above code, we declared an array of pointer names as 'names' of size 5. In the above case, we have done
the initialization at the time of declaration, so we do not need to mention the size of the array of a pointer. The
above code can be re-written as:
In the above case, each element of the 'names' array is a string literal, and each string literal would hold the
base address of the first character of a string. For example, names[0] contains the base address of "john",
names[1] contains the base address of "Peter", and so on. It is not guaranteed that all the string literals will be
stored in the contiguous memory location, but the characters of a string literal are stored in a contiguous
memory location.
1. #include <iostream.h>
2. int main()
3. {
4. char *names[5] = {"john",
5. "Peter",
6. "Marco",
7. "Devin",
8. "Ronan"};
9. for(int i=0;i<5;i++)
10. {
11. std::cout << names[i] << std::endl;
12. }
13. return 0;
14. }
In the above code, we have declared an array of char pointer holding 5 string literals, and the first character of
each string is holding the base address of the string.
Output :
___________________________________________________________________________________Q1.
Q1. Write a C+ + program to find out the sum of n numbers.
Q8. What is the difference between variable and constant in C++ programming language?
Q9. What do you mean by global variable and local variable in C++?
Q13. What is friend class? Write a program to illustrate the concept of friend class.
CHAPTER – 04
4.4 DESTRUCTOR
OUTPUT :
1. The constructors are always declared in the public section. If declared in the private section then
objects are can only be created inside the member functions but serve no purpose.
2. They are invoked automatically when objects of the class are created. The declaration demo d;
creates an object d which automatically calls the constructor of the class and prints Hello from
constructor.
3. They do not have any return type not even void so they cannot return any value.
4. Constructors cannot be inherited, but they can be called from the constructors of derived
class.
5. Constructors are used to construct the object of the class.
6. The constructor with no argument is known as default constructor of the class. The default
constructor for the class demo will be demo : demo( )
7. Constructors which take arguments like a function takes are known as parameterized
constructor.
8. There is no limit of the number of constructors declared in a class but they all must
conform to rules of function overloading.
9. Constructor can have default arguments.
10. Addresses of constructors cannot be taken.
11. Constructors cannot be virtual.
12. Constructor make implicit calls to operators new and delete in case memory allocation and
de- allocation is to be performed.
#include <iostream.h>
#include <conio.h>
class demo
{
int a,b;
public :
demo( )
{
a=b=0;
cout<<“Zero argument constructor called\n”;
show( );
}
demo(int x, int y)
{
a=x;
b=y;
cout<<“Two argument constructor called\n”;
show( );
}
demo(int x)
{
a=b=x;
cout<<“One argument constructor called\n”;
show( );
}
void show( )
{
cout<<“a=”<<a<<“\tb=”<<b<<endl;
}
};
void main( )
{
clrscr( );
demo d1;
demo d2(10,20);
demo d3(30);
getch( );
}
OUTPUT :
4.4 DESTRUCTOR
______________________________________________________________________________________________
A destructor is a member function of the class whose name is same as the name of the class
but the preceded with tilde sign (~). The purpose of destructor is to destroy the object when
it is no longer needed or goes out of scope. As a very small example of destructor see the
program given below :
#include <iostream.h>
#include <conio.h>
class demo
{
public :
demo( )
{
cout<<“Constructor called\n”;
}
~demo( )
{
cout<<“Destructor called”<<endl;
}
};
void main( )
{
clrscr( );
demo d;
getch( );
}
OUTPUT :
Constructor called
Destructor called
CHAPTER – 05
Polymorphism
Chapter Structure :.
5.0 Polymorphism
5.0 Polymorphism
__________________________________________________________________________________________
Polymorphism is the ability to use an operator or method in different ways. Polymorphism gives
different meanings or functions to the operators or methods. Poly refers many that signify the
many uses of these operators and methods. A single method usage or an operator functioning in
many ways can be called polymorphism. Polymorphism refers to codes, operations or objects
that behave differently in different contexts. “Polymorphism is a mechanism that allows you to
implement a function in different ways.”
Polymorphism plays an important role in allowing objects having different internal structures to
share the same external interface. This means that a general class of operations may be accessed
in the same manner even though specific actions associated with each operation may differ.
The same + operator can be used with different meanings with strings:
"Tech" + "nical"
The same + operator can be also used for floating point addition: 2.15 + 10.20
We saw above that a single operator „+‟ behaves differently in different contexts such as integer,
string or float referring the concept of polymorphism. The above concept leads to operator
overloading. When the exiting operator or function operates on new data type it is overloaded.
C++ also permits the use of different functions with the same name. Such functions have
different argument list. The difference can be in terms of number or type of arguments or both. It
refers as function overloading. So, we conclude that the concept of operator overloading and
function overloading is a branch of polymorphism. Both the concepts have been discussed in unit
2 in detail.
Function overloading
Operator overloading
Virtual functions
Function
Overloading
Compiletime
Polymorphism
Operator
Polymorphism Overloading
in C++
Runtime Virtual
Polymorphism Function
This trivial function adds two integers. However, what if we also need to add two floating point
numbers? This function is not at all suitable, as any floating point parameters would be converted
to integers, causing the floating point arguments to lose their fractional values.
One way to work around this issue is to define multiple functions with slightly different names:
#include<iostream.h>
// function prototype
int func(int i);
int func(int i, int j);
void main(void)
{
cout<<func(15); //func(int i)is called
cout<<func(15,15); //func(int i, int j) is called
}
int func(int i)
{
return i;
}
int func(int i, int j)
{
return i+j;
}
#include<iostream.h>
//function prototypes
int func(int i);
double func(double i);
void main(void)
{
cout<<func(15); //func(int i) is called
cout<<func(15.155); //func(double i) is called
}
int func(int i)
{
return i;
}
double func(double i)
{
return i;
}
Data conversion
Only built-in operators can be overloaded. If some operators are not present in C++, we
cannot overload them.
The arity of the operators cannot be changed
The precedence of the operators remains same.
The overloaded operator cannot hold the default parameters except function call operator
“()”.
We cannot overload operators for built-in data types. At least one user defined data types
must be there.
The assignment “=”, subscript “[]”, function call “()” and arrow operator “->” these
operators must be defined as member functions, not the friend functions.
Some operators like assignment “=”, address “&” and comma “,” are by default
overloaded.
class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void) {
return length * breadth * height;
}
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
Output :-
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
int main() {
Distance D1(11, 10), D2(-5, 11);
return 0;
}
Output :-
F: -11 I:-10
F: 5 I:-11
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
return false;
}
};
int main() {
Distance D1(11, 10), D2(5, 11);
if( D1 < D2 ) {
cout << "D1 is less than D2 " << endl;
} else {
cout << "D2 is less than D1 " << endl;
}
return 0;
}
Output :-
D2 is less than D1
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
void operator = (const Distance &D ) {
feet = D.feet;
inches = D.inches;
}
int main() {
Distance D1(11, 10), D2(5, 11);
return 0;
}
Output :-
First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11
A constructor is used to build a matrix object from an int type array. Similarly, we used another
constructor to build a string type object from char* type variable. In below examples
constructors performed a defacto type conversion from the argument's type to the constructor's
class type.
string :: string(char*a)
{
length = strlen(a);
name = new char [len + 1];
strcpy(name,a);
}
This constructor builds a string type object from char* type variable a. The variables length and
name are data members of the class string. Once we define the constructor in the class string, it
can be used for conversion from char* type to string type.
Example 1:
string s1 , s2;
char* name1 = " Good Morning " ;
char* name2 = " Students " ;
s1 = string ( name1 ) ;
s2 = name2 ;
Explanation :-
s1 = string ( name1 ) ;
In the above code snippet, first converts name1 from char* type to string type and then assigns
the string type values to the object s1.
The statement below performs the same job by invoking the constructor implicitly.:
s2 = name2 ;
Example 2:
class time
{
int hours;
int minutes;
public :
void time ( int t ) // II constructor
{
hours = t / 60 ; // t is inputted in minutes
minutes = t % 60 ;
}
};
Explanation :-
Note : In both the examples, the left-hand operand of = operator is always a class object. Hence,
we can also accomplish this conversion using an overloaded = operator.
The general syntax of an overloaded casting operator function, also referred to as a conversion
function, is :
operator typename()
{
// Program statement
}
Example :
In the below example, operator double () converts a class object to type double.
We have just seen data conversion techniques from a basic to class type and a class to basic type.
But sometimes we would like to convert one class data type to another class type.
Example :
obj1 is an object of class one and obj2 is an object of class two. The class two type data is
converted value is assigned to the obj1. Since the conversion takes place from class two to class
one, two is known as the source and one is known as the destination class.
Such conversion between objects of different classes can be carried out by either a constructor or
a conversion function. Which form to use, depends upon where we want the type-conversion
function to be located, whether in the source class or in the destination class.
This function converts the class object of which it is a member to typename. The typename may
be a built-in type or a user defined one( another class type ). In the case of conversions between
objects, typename refers to the destination class. Therefore, when a class needs to be converted, a
casting operator function can be used. The conversion takes place in the source and the result is
given to the destination class.
The following program uses classes and shows how to convert data of one type to another :
#include <iostream>
using namespace std;
class stock2 ;
class stock1
{
int code , item ;
float price ;
public :
stock1 ( int a , int b , int c )
{
code = a ;
item = b ;
price = c ;
};
void disp ()
{
cout << " code " << code << " \n " ;
cout << " items " << item << " \n " ;
cout << " price per item Rs. " << price << " \n " ;
};
int getcode ()
{ return code; };
int getitem ()
{ return item ; };
int getprice ()
{ return price ; };
operator float ()
{
return ( item*price ) ;
};
};
class stock2
{
int code ;
float val ;
public :
stock2 ()
{
code = 0;
val = 0 ;
};
stock2( int x , float y )
{
code = x ;
val = y ;
};
void disp ()
{
cout << " code " << code << " \n " ;
cout << " total value Rs. " << val << " \n " ;
};
stock2( stock1 p )
{
code = p.getcode() ;
val = p.getitem() * p.getprice() ;
};
};
int main()
{
stock1 i1 ( 101 , 10 ,125.0 ) ;
stock2 i2 ;
float tot_val = i1;
i2 = i1 ;
cout << " Stock Details : Stock 1 type " << " \n " ;
i1.disp ();
cout << " Stock Value " << " - " ;
cout << tot_val << " \n " ;
cout << " Stock Details : Stock 2 type " << " \n " ;
i2.disp () ;
return 0 ;
}
Q1. What are the basic rules for operator overloading in C++?
Q2. What is dynamic binding?
Q3. Describe the concept of polymorphism
Q4. What is function overloading?
Q5. What are the main applications of function overloading?
Q6. Explain the concept of operator overloading?
Q7. What are the limitations of Operator overloading and Functional overloading?
UNIT – III
CHAPTER – 06
Virtual Functions
Chapter Structure :
1. #include <iostream.h>
2. {
3. public:
4. virtual void display()
5. {
6. cout << "Base class is invoked"<<endl;
7. }
8. };
9. class B:public A
10. {
11. public:
12. void display()
13. {
14. cout << "Derived Class is invoked"<<endl;
15. }
16. };
17. int main()
18. {
19. A* a; //pointer of base class
20. B b; //object of derived class
21. a = &b;
22. a->display(); //Late Binding occurs
23. }
Output:
The first and foremost question which is arises why do we need virtual function? Suppose we do
have a list of pointer to objects of a super class in an inheritance hierarchy and we wish to invoke
the functions of its derived classes with the help of single list of pointers provided that the
functions in super class and sub classes have the same name and signature. That in turn means
we want to achieve run time polymorphism.
Example :-
1. #include <iostream.h>
2. class Base
3. {
4. public:
5. virtual void show() = 0;
6. };
7. class Derived : public Base
8. {
9. public:
10. void show()
11. {
12. std::cout << "Derived class is derived from the base class." << std::endl;
13. }
14. };
15. int main()
16. {
17. Base *bptr;
18. //Base b;
19. Derived d;
20. bptr = &d;
21. bptr->show();
22. return 0;
23. }
Output:
_____________________________________________________________________________________
Static functions and members can be simply defined as the functions and members which can be
accessed through the class name. We do not need to create the instance/object of the class in
order to access the static members of the class. Static members are per class where as non-static
members are per instance. An interesting thing is that value of the static members of the class is
same for all objects and if static member is publicly defined, any object of the class can modify
the value of static members and this value will be updated for all the instances.
#include <iostream.h>
#include <fstream.h>
#include <string.h>
class ObjectCounter
{
public:
static int numofobjects;
public:
ObjectCounter()
{
numofobjects ++;
}
static void showcount()
{
cout<<"Total number of Objects is: "<<numofobjects<<endl;
}
};
int main()
{
ObjectCounter::showcount();
ObjectCounter a, b, c;
cout<<"After instantiating ObjectCounter Class thrice."<<endl;
ObjectCounter::showcount();
}
#include <iostream>
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(5.6, 1.2, 5.1); // Declare box1
Box Box2(2.5, 4.1, 6.1); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
Output :
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
An abstract class can not be instantiated that means abstract classes can not have their
own instances but their child or derived classes may have their own instances provided
the child class itself is not an abstract class.
Though objects of an abstract class cannot be created, however, one can use pointers and
references to abstract class types.
A class should contain at least one pure virtual function to be called as abstract. Pure
virtual functions can be declared with the keyword virtual and =0 syntax at the end of
function declaration statement.
If a class is made abstract by giving a pure virtual function then it must be inherited by a
child class of it that provides the implementation of the pure virtual function.
If a class inherits an abstract class and does not provide the implementation of the pure
virtual function then the child class itself should declare the function as pure virtual that
means the child class will be an abstract class as well.
The signature of the function declared as pure virtual in base class must strictly agree
with the signature of the function in child class that implements the pure virtual function.
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
Output :-
A destructor in C++ is a member function of a class used to free the space occupied by or delete
an object of the class that goes out of scope. A destructor has the same name as the name of the
constructor function in a class, but the destructor uses a tilde (~) sign before its function name.
Virtual Destructor
A virtual destructor is used to free up the memory space allocated by the derived class object or
instance while deleting instances of the derived class using a base class pointer object. A base or
parent class destructor use the virtual keyword that ensures both base class and the derived class
destructor will be called at run time, but it called the derived class first and then base class to
release the space occupied by both destructors.
When an object in the class goes out of scope or the execution of the main() function is about to
end, a destructor is automatically called into the program to free up the space occupied by the
class' destructor function. When a pointer object of the base class is deleted that points to the
derived class, only the parent class destructor is called due to the early bind by the compiler. In
this way, it skips calling the derived class' destructor, which leads to memory leaks issue in the
program. And when we use virtual keyword preceded by the destructor tilde (~) sign inside the
base class, it guarantees that first the derived class' destructor is called. Then the base class'
destructor is called to release the space occupied by both destructors in the inheritance class.
1. #include<iostream>
2. using namespace std;
3. class Base
4. {
5. public:
6. Base() // Constructor member function.
7. {
8. cout << "\n Constructor Base class"; // It prints first.
9. }
10. virtual ~Base() // Define the virtual destructor function to call the Destructor Derived function.
11. {
12. cout << "\n Destructor Base class"; /
13. }
14. };
15. // Inheritance concept
16. class Derived: public Base
17. {
18. public:
19. Derived() // Constructor function.
20. {
21. cout << "\n Constructor Derived class" ; /* After print the Constructor Base, now it will prints.
*/
22. }
23. ~Derived() // Destructor function
24. {
25. cout << "\n Destructor Derived class"; /* The virtual Base Class? Destructor calls it before call
ing the Base Class Destructor. */
26. }
27. };
28. int main()
29. {
30. Base *bptr = new Derived; // A pointer object reference the Base class.
31. delete bptr; // Delete the pointer object.
32. }
Output: