0% found this document useful (0 votes)
13 views140 pages

BCA Sem 3 C - SSCCM

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views140 pages

BCA Sem 3 C - SSCCM

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 140

Swami Sahajanand College of Information Technology BCA SEM -3

Swami Sahajanand College of Computer Science

B.C.A. SEM. - 3

Object Oriented Programming with C++

Subject : Object Oriented Programming with C++


1
Swami Sahajanand College of Information Technology BCA SEM -3

UNIT - 1

Subject : Object Oriented Programming with C++


2
Swami Sahajanand College of Information Technology BCA SEM -3

UNIT - 1

Principal Of Object Oriented Programming

◆ Introduction of OOP, OOP V/s POP


◆ Concept of OOP – Object, Class, Inheritance, Encapsulation, Polymorphism,
Abstraction, Message Passing
◆ Structure Of C++ Program
◆ Tokens in C++
◆ Data type, Constant, Variable, Statement & Operators
◆ Function – Member function, Inline function, Friend function
◆ Input/output statements
◆ Declaration & Creation of Class and Object

Subject : Object Oriented Programming with C++


3
Swami Sahajanand College of Information Technology BCA SEM -3

◆ Introduction of OOP

Object Oriented Programming


• In OOP, the complex task is divided into small manageable modules (known as Objects) but
equal importance is given to both the Data and Functions.
• The data of an object can be accessed only by the function associated with that Object.
• The fundamental idea behind Object Oriented languages is to combine both Data and
Functions into single unit and that operate on data, such unit is called an Object.
• An Object’s function (known as Member Function) in C++ provides facility to access its data.
So, when you need to read data item in an object, you call a member function in that object.
• Note that, you cannot access data directly because the Data is hidden, so it is safe from
accidental change.
• Data and functions are said to be encapsulated into single entity. So data encapsulation and
data hiding are important in description of Object Oriented Languages.
• The organization of Data and Functions in Object oriented Programs is shown in diagram.

Characteristics/Features of Object Oriented Programming

• Emphasis (importance) is on data.


• Programs are divided into smaller modules known as Objects.
• Data and functions are tied together in data structure.
• Data is hidden and cannot be accessed by external functions.

Subject : Object Oriented Programming with C++


4
Swami Sahajanand College of Information Technology BCA SEM -3

• Objects may communicate with each other with the help of Member Functions.
• New data and functions can be easily added whenever necessary through concept of
inheritance.
• It follows Bottom to Top approach. (bottom up)
Advantages of OOP

• In this approach, a program or system is seen as a collection of objects, each with a


functional purpose. Since the objects represent real-world objects, OOP approach is more
suitable for real-world problems.
• The principle of data hiding helps the programmers to build secure programs, that cannot
be accessed by the code in other parts of program.
• Through Inheritance, we can eliminate redundant code and extend the use of existing class.
So objects can be reused in different applications. Thus this approach promotes reuse of
code in large programs/systems.
• It is easy to partition the work based on object, means different object have different data
stored in different partitions of memory, so problem of data loss can be solved.
• OOP can be easily upgrade from small system to large systems because object oriented
programs are more flexible and can be changed easily.
• Using OOP concept, Designing and software complexity can be easily managed and repairing
faults in program/system is much easier and faster.
• Using concept of Operator Overloading, we can provide additional task to the Operator,
without changing its meaning.
• Using concept of Dynamic Binding, we can select proper function at runtime.

Applications of C++

• Real-time systems.
• Simulation and modeling.
• Object-oriented databases.
• Hypertext, hypermedia and expert text.
• AI (Artificial Intelligence) and expert systems.

Subject : Object Oriented Programming with C++


5
Swami Sahajanand College of Information Technology BCA SEM -3

• Neural networks and parallel programming.


• Decision support and office automation systems.
• CIM/CAM/CAD systems.

Differences between C & C++ OR OOP V/S POP

C C++
Language Language
It is developed by Denis Ritchie. It is developed by Bjarne Stroustrup.
It is Only C (without classes). It is C with Classes.
It is Procedure Oriented It is Object Oriented Programming
Programming (POP) language. (OOP)language.

It follows Top-down approach. It follows Bottom-up approach.

Data move freely around the Data is hidden and cannot be


system from function to function. accessed by external functions.
A program is divided into function. A program is divided into objects.

Security not maintains to hide data Security is maintaining to hide data in


in C. C++.

Software complexity cannot be Software complexity can be easily


easily managed. managed using reusability of code.
In C, we declare variable at the top In C++, we can declare variable
of program. anywhere in the program.

◆ Concept of OOP
• The prime purpose of C++ programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming languages.
• The core of the pure object-oriented programming is to create an object, in code, that
has certain properties and methods. While designing C++ modules, we try to see whole
world in the form of objects.

Subject : Object Oriented Programming with C++


6
Swami Sahajanand College of Information Technology BCA SEM -3

• For example a car is an object which has certain properties such as color, number of doors,
and the like. It also has certain methods such as accelerate, brake, and so on.

1. Object:

• Object is the basic unit of object oriented programming. That is both data and function
that operate on data are bundled as a unit called as object.
• Objects are the basic run-time entities in an object – oriented system.
• Object may represent a person, a place, a bank account, a table of data or any item that
the program has to handle.
• Objects can interact without having to know details of each other’s data or code.
• Objects take up space in the memory.
Object : EMP
DATA:
Emp_No.
Name
Departmen
t Basic
Salary

Subject : Object Oriented Programming with C++


7
Swami Sahajanand College of Information Technology BCA SEM -3

FUNCTIONS:
getdata() (Input)
total() (Find Total
Salary)display() (Output)
2. Class:

• When you define a class, you define a blueprint for an object. This doesn't actually
define any data, but it does define what the class name means, that is, what an object of the
class will consist of and what operations can be performed on such an object.
• “A class is thus a collection of data member and function.”
• The class body contains the declaration of variables and functions.
• The class members that have been declared as private can be accessed only from withinthe
class.
• The body of a class is enclosed within braces and terminated by a semicolon.
• The key-words private and public are known as visibility labels.
• By default, the members are private in a class.
Syntax :
class classname
{
private:
data member; function;
public:
data member; function;};
3. Abstraction:
• Data abstraction refers to, providing only essential information to the outside world and
hiding their background details i.e. to represent the needed information in program without
presenting the details.
• “Abstraction is the act of representing essential features without including the
background details or explanations.”
• Since the classes use the concept of data abstraction, they are known as Abstract Data
Types.
• For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world
without giving internal detail about those methods and data.
4. Encapsulation:

Subject : Object Oriented Programming with C++


8
Swami Sahajanand College of Information Technology BCA SEM -3

• Encapsulation is placing the data and the functions that work on that data in the same
place.
• “The wrapping up of data and functions into a single unit (called class) is known as
encapsulation.”
• Encapsulation is a programming mechanism that binds together code and the data it
manipulates, and that keeps both safe from outside interference and misuse.
• The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it.
5. Inheritance:

• One of the most useful aspects of object-oriented programming is code reusability. As the
name suggests Inheritance is the process of forming a new class from an existing class that is
from the existing class called as base class, new class is formed called as derived class.
• This is a very important concept of object oriented programming since this feature helps to
reduce the code size.
• “Inheritance is the process by which objects of one class acquire the properties ofobjects
of another class.”
• Using a concept called inheritance new classes can be built from the old ones.
• The new class referred to as a derived class, can inherit the data structures andfunctions
of the original, or the base class.
• The new class can add data elements and functions to those it inherits from its base
class.
• It supports the concept of hierarchical classification. For example, the ‘Bike’ is a part ofthe
class ‘Petrol’ which is again a part of the class ‘Vehicle’.
• “Inheritance is the process by which objects of one class acquire the properties ofobjects
of another class.”
• Using a concept called inheritance new classes can be built from the old ones.
• The new class referred to as a derived class, can inherit the data structures andfunctions
of the original, or the base class.
• The new class can add data elements and functions to those it inherits from its base
class.
• It supports the concept of hierarchical classification. For example, the ‘Bike’ is a part ofthe
class ‘Petrol’ which is again a part of the class ‘Vehicle’.

Subject : Object Oriented Programming with C++


9
Swami Sahajanand College of Information Technology BCA SEM -3

Vehicle

Attribute

For Wheeler

Two Wheeler

Patrol Diesel

Attributes Attributes

………… .………..

Bile Scooter Car Truck

Attributes Attributes Attributes Attributes

6. Polymorphism:
………… .……….. ………… .………..
• The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers
many. That is a single function or an operator functioning in many ways different upon the
usage is called polymorphism.
• Polymorphism is a Greek term, means the ability to take more than one form.
• “Polymorphism means one name multiple forms.”
• An operation may exhibit different behaviors in different instances. The behavior depends
upon the types of data used in the operation.
• There are two types of polymorphism: Compile time and Runtime.
• Function Overloading and Operator overloading are example of compile time
polymorphism.
• Virtual function is a example of Runtime polymorphism.
• The different behaviors in different instances are known as operator overloading.
• Using a single function name to perform different types of tasks is known as function
overloading.

Subject : Object Oriented Programming with C++


10
Swami Sahajanand College of Information Technology BCA SEM -3

Polymorphism

Run time
polymorphism

Virtual functions or
Dynamic Binding

7. Dynamic Binding:

• “Dynamic binding (late binding) means that the code associated with a given procedurecall
is not known until the time of the call at run-time.”
• Binding refers to the linking of a procedure call to the code to be executed in response tothe
call.
• A function call associated with a polymorphic reference depends on the dynamic type of
that reference.

8. Message Passing:

• “One object communicates with other object to send information is known as message
passing.”
• An object oriented program consists of a set of objects that communicate with each other.
• Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another.
Structure of C++ Program

• A C++ program is structured in a specific and particular manner. In C++, a program is

Subject : Object Oriented Programming with C++


11
Swami Sahajanand College of Information Technology BCA SEM -3

divided into the following three sections:


▪ Standard Libraries Section
▪ Main Function Section
▪ Function Body Section
Standard libraries section
#include<iostream.h>
#include<conio.h>
• #include is a specific preprocessor command that effectively copies and pastes the entire text
of the file, specified between the angle brackets, into the source code.
• The file <iostream>, which is a standard file that should come with the C++ compiler, is short
for input-output streams. This command contains code for displaying and getting an input
from the user.
• namespace is a prefix that is applied to all the names in a certain set. iostream file defines two
names used in this program - cout and endl.
• This code is saying: Use the cout and endl tools from the std toolbox.
Main function section

• The starting point of all C++ programs is the main function.


• This function is called by the operating system when your program is executed by the
computer.
• { signifies the start of a block of code, and } signifies the end.

Function body section

• The name cout is short for character output and displays whatever is between
the << brackets.
• Symbols such as << can also behave like functions and are used with the keyword cout.
• The return keyword tells the program to return a value to the function int main
• After the return statement, execution control returns to the operating system component
that launched this program.
• Execution of the code terminates here.

Tokens in C++

• C++ Tokens are the smallest individual units of a program.


• C++ is the superset of C and so most constructs of C are legal in C++ with their meaning and
usage unchanged. So tokens, expressions, and data types are similar to that of C.

Subject : Object Oriented Programming with C++


12
Swami Sahajanand College of Information Technology BCA SEM -3

• Following are the C++ tokens : (most of c++ tokens are basically similar to the C tokens)
▪ Keywords
▪ Identifiers
▪ Constants
▪ Variables
▪ Operators
1. Keywords
• Keywords are reserved words which have fixed meaning, and its meaning cannot be changed.
The meaning and working of these keywords are already known to the compiler. C++ has more
numbers of keyword than C, and those extra ones have special working capabilities.
• There are 32 of these, and here they are

auto const double float int short struct unsigned


break continue elseforlong signed switch void

case default enumgoto register sizeof typedef volatilechar


do extern if return static unionwhile

• There are another 30 reserved words that were not in C, are therefore new to C++, and here
they are -
asm dynamic_cast namespace reinterpret_cast trybool
explicit new static_cast typeid 2. I
dentifie
catch false operator template typename
class friend privatethis using const_cast
rs
inline public throw virtualdelete mutable •I
protected true wchar_t dentifi
ers are names given to different entries such as variables, structures, and functions. Also,
identifier names should have to be unique because these entities are used in the execution of
the program.
• Identifier naming conventions
o Only alphabetic characters, digits and underscores are permitted.
o First letter must be an alphabet or underscore (_).
o Identifiers are case sensitive.
o Reserved keywords can not be used as an identifier's name.
3. Constants
• Constants are like a variable, except that their value never changes during execution once
defined.
• There are two other different ways to define constants in C++. These are:
o By using const keyword

Subject : Object Oriented Programming with C++


13
Swami Sahajanand College of Information Technology BCA SEM -3

o By using #define preprocessor


Declaration of a constant :

const [data_type] [constant_name]=[value];


4. Variabl
e
• A variable is a meaningful name of data storage location in computer memory. When
using a variable you refer to memory address of computer.
Syntax to declare a variable

[data_type] [variable_name];

5. Example Operator

#include <iostream.h>

int main() {

int a,b;// a and b are integer variable

cout<<" Enter first number :";

cin>>a;

cout<<" Enter the second number:";

cin>>b;

int sum;

sum=a+b;

cout<<" Sum is : "<<sum <<"\n";

return 0;

C++
}
operator is a symbol that is used to perform mathematical or logical manipulations.

• Arithmetic Operators
• Increment and Decrement Operators

Subject : Object Oriented Programming with C++


14
Swami Sahajanand College of Information Technology BCA SEM -3

• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Arithmetic Operator

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

Increment and Decrement Operators

Operator Description
++ Increment
−− Decrement

Relational Operators
Operator Description

== Is equal to
!= Is not equal to
> Greater than
< Less

Subject : Object Oriented Programming with C++


15
Swami Sahajanand College of Information Technology BCA SEM -3

>= Greater than or equal to


<= Less than or equal to

Logical Operators

Operator Description
&& And operator. Performs logical conjunction of two
expressions.(if both expressions evaluate to True, result is
True. If either expression evaluates to False, the result is
False)
|| Or operator. Performs a logical disjunction on two
expressions.(if either or both expressions evaluate to True,
the result is True)

Operator Description

! Not operator. Performs logical negation on an expression.

Bitwise Operators
Operator Description

<< Binary Left Shift Operator


!= Is not equal to
>> Binary Right Shift Operator
~ Binary One's Complement Operator
& Binary AND Operator
^ Binary XOR Operator

Subject : Object Oriented Programming with C++


16
Swami Sahajanand College of Information Technology BCA SEM -3

| Binary OR Operator
Assignment Operators

Operator Description
= Assign
+= Increments, then assign
-= Decrements, then assign
*= Multiplies, then assign
/= Divides, then assign
%= Modulus, then assigns
<<= Left shift and assigns
>>= Right shift and assigns
&= Bitwise AND assigns
^= Bitwise exclusive OR and assigns
|= Bitwise inclusive OR and assigns
Misc Operators
Operator Description

, Comma operator
sizeof() Returns the size of a memory location.
& Returns the address of a memory location.
* Pointer to a variable.
?: Conditional Expression

Subject : Object Oriented Programming with C++


17
Swami Sahajanand College of Information Technology BCA SEM -3

Data Types, Variables, Constants, Statements & Operators


Data Types

• Fundamental (Basic) Data Types


• C++ provides the following fundamental built-in data types:

Data Type Used For

Void Associated with no data type


int Integer values
float Floating point values
double Double precision floating point number
char Characters
wide char Wide Character

Size
Type Range
In Bytes
char / signed char 1 -128 to 127
unsigned char 1 0 to 255
int 1 -32768 to 32767
unsigned int /unsigned
2 0 to 65535
short int
signed int / short int
2 -32768 to 32767
/signed short int
long int -2147483648 to
4
signed long int 2147483647
unsigned long int 4 0 to 4294967295
float 4 3.4E-38 to 3.4E+38

Boolean value: True or False Size and Range of C++ Basic Data Types

Integer Types:

Subject : Object Oriented Programming with C++


18
Swami Sahajanand College of Information Technology BCA SEM -3

• The integer type is used for storing whole numbers without decimal points.
• We can use signed, unsigned or plain integer as follows.
• signed int i = 123; (Signed with positive value)
• signed int x = - 25; (Signed with Negative value)
• unsigned int count = 0; (unsigned value always positive)
• int y = -25 (Plain integer can always hold positive or negative values and always signed)
Floating-Point Types:

double 8 1.7E-308 to 1.7E+308


long double 10 3.4E-4932 to
1.1E+4932

• Floating point types can contain decimal numbers.


• There are three sizes: float(single-precision) ,double(double-precision) and long
double(extended-precision).
• float Celsius = 31.58;
• double Fahrenheit = 123.456;
• long double ac_bal = 20145.45;
Character Types:
• The character type is used to store characters and character is enclosed within single
quotes.
• char ch = ‘a’;
• char uv = ‘7’;
• we can also assign numeric values to variables of character type : char chNumber = 34;
• We can declare signed and unsigned characters.
• signed char myChar = 10; (signed with positive value)
• signed char newChar = -32 (signed with negative value)
• unsigned char newChar = 300; (unsigned have only positive values)
Strings:
• Variables that can store non numerical values that are longer than one single characterare
known as strings.
• char str[];
Boolean Type:
• The Boolean type can have the value true or false.
• bool is_Alive = false;

Subject : Object Oriented Programming with C++


19
Swami Sahajanand College of Information Technology BCA SEM -3

• bool key_found = true;


• if a Boolean value is converted to integer value, true becomes 1 and false becomes 0.
• If an integer value is converted to a Boolean value, 0 becomes false and non-zero becomes
true.
User Defined Data Types:

• User defined data types are structure, union, class and enumeration.

Enumeration Type:

• An enumeration type is a user defined data type that enables the user to define the range of
values for the type.
• Named constants are used to represent the values of an enumeration.
enum status
{
single,engaged,married} status
s=single;
if (s==engaged)
{
//perform something
}
• The default values assigned to the enumeration constants are zero-based, so in above
example single=0, engaged=1,married=2.
• User can assign different value to one or more of the enumeration constants and
subsequent values that are not assigned a value will be incremented.
• Enum fruit {banana=2,orange=5,apple,pinapple=9,kiwi}
• In above example apple will have value 6 and kiwi have value 10.
Structure Type:

• A structure is a collection of simple variables.


• The variable in s structure can be of different types, such as, int, float, char etc.
• Data items in structure is called the members of structure.

Syntax: struct name


{
Example:

Subject : Object Oriented Programming with C++


20
Swami Sahajanand College of Information Technology BCA SEM -3

Declaration of data members of structure


}
Structure variables;
struct employee
{ char
name[20]; int
age;
}e;
• You can access data member of structure by using only structure variable with dotoperator.

Union:
union data
{
Char ch[2];
int I;
};

Derived Data Types:

• Derived data types are array, function and pointers.


Array:

• An array is a series of elements of the same type placed in contiguous memory locations.
• Syntax: type name[elements]
• Where type is a valid type like int float or char, name is a valid identifier and the elements
field(always enclosed in square brackets [ ] ) specifies how many of these elements the array
has to contain.
• Arrays are of two types.
1) Static array

• int student[10] example of static array


• The number between brackets tells the compiler how many contiguous memory
locations need to be reserved. In above example It will occupy 10 memory locations.

Subject : Object Oriented Programming with C++


21
Swami Sahajanand College of Information Technology BCA SEM -3

2) Dynamic array
• int student[ ] example of dynamic array
• Dynamic array are created in the heap using new and released using delete operation.
Pointers:

• pointer is a variable that holds a memory address of another variable.


• Declaring a pointer doesn’t reserve any memory for the array that will be reserved with new.
int *student;
student = new int[10];

• The new operator is requesting 10 integer elements from heap. Dynamic array allocation is
good because the size of the array can be determined at run-time and then used with new
operator to reserve space in heap.
• A pointer is also used with string;
char *name = “Hello”; //which is called constant pointer or string constant.
Dynamic Initialization of Variables:

• C++ permits initialization of the variables at run time. This is referred as dynamic
initialization.
• In C++, a variable can be initialized at run time using expressions at the place ofdeclaration.
For Example :
int n = strlen(string);

float average = sum/i;

Reference variables:

• Reference variable provides an alias for a previously defined variable.


• A reference variable is created as follows :
Syntax: - data-type & reference-name = variable-

name; Example: - int total = 100;

int & sum = total;


• In above example sum is the alternative name declared to represent the variable total.
Both the variables refer to the same data object in the memory.
• A reference variable must be initialized at the time of declaration.
• Example Program :

Subject : Object Oriented Programming with C++


22
Swami Sahajanand College of Information Technology BCA SEM -3

#include<iostream.h>
#include<conio.h>
void main()
{
int x=10;
int&
ref=x;
cout<<"x is "<<x<<" and ref is "<<ref<<endl;
cout<<"change ref to 25"<<endl;
ref=25;
cout<<"x is "<<x<<" and ref is "<<ref<<endl;
getch();
}
• A point of reference variables and functions is that you can pass variable as a parameterand
have the variable changed in the function. Like in following example :
#include<iostream.h>
#include<conio.h>
void func(int &x); //Function
protoytpe void main()
{
clrscr();
Int var; var=10;
cout<<”Var is : ”<<var<<endl;
func(var);
cout<<”Now Var is : ”<<var<<endl;
getch();
}
void func(int &x)
{
x=x*2;

C++ KEYWORDS:

ASM CATCH CLASS DELETE

Subject : Object Oriented Programming with C++


23
Swami Sahajanand College of Information Technology BCA SEM -3

FRIEND INLINE NEW OPERATOR


PRIVATE PROTECTED PUBLIC TEMPLETE

THIS THROW TRY VIRTUAL

• All C language reserved words are available in C++ and in addition above reserved wordsare
added to it.

Rules of identifiers:

• Identifier refers to the names of variables, functions, arrays, classes etc. created by the
programmer.
• They are the fundamental requirements of any language.
• Each language has its own rules for naming these identifiers.
• The following rules are common to both C and C++.
• Only alphabetic characters, digits and underscores are permitted.
• The name cannot start with a digit.
• Uppercase and lowercase letters are distinct.
• A declared keyword cannot be used as a variable name.
• A major difference between C and C++ is the limit on the length of a name. while ANSI C
recognize only the first 32 characters in a name while ANSI C++ places no limit on its length
and therefore all the characters in a name are significant.
Constant:

• Constants refer to fixed values that do not change during the execution of a program.
• You must initialize a constant when you create it, and you cannot assign a new value later,
after a constant is initialized.
• C++ has two types of constants: Literal and Symbolic.
• A literal constant is a value typed directly into your program wherever it is needed.
• For example: int Age = 25;
• Age is a variable of type int, 25 is a literal constant. We can’t assign a value to 25 and it
cannot bechanged.
• Symbolic Constants: A symbolic constant is a constant that is represented by a name, justas a
variable But unlike variable, after initialization its value can’t be changed.
Defining Constants with #define :

Subject : Object Oriented Programming with C++


24
Swami Sahajanand College of Information Technology BCA SEM -3

• For example : #define Age 25


• Note that student is of no particular type like int, char, float, etc.
• #define does a simple text substitution. Every time the preprocessor sees the word Age, itwill
put 25 in text.
• Because the preprocessor runs before compiler, your compiler never sees your constant,it
sees only number 25.
Defining Constants with const :

• we can use const in a constant expression, such as :


const Age = 25; is same as const int Age = 25; because it is default to integer(int).
Typedef Statement

• It is difficult task to write and repeat typing unsigned short int every time in program.
• C++ gives facility to use alias for unsigned short int by using keyword typedef which
stands for type definition.
• Syntax : typedef existing_type new_name;
• Example :
#include<iostream.h>
#include<conio.h>
typedef unsigned short int
USHORT; void main()
{
USHORT
width=5;
USHORT length;
length=25;
USHORT area=width*length; //Dynamic Initialization of
variable cout<<"\nWidth : "<<width;
cout<<"\nlength : "<<length<<"\n"; cout<<"area : "<<area;
getch();
}

Constant Expression:

• Which consist of only constant values. We cannot use variable with it, when we use

Subject : Object Oriented Programming with C++


25
Swami Sahajanand College of Information Technology BCA SEM -3

constant. We directly give value. It may be int, float or char value. For e.g.
15 ‘x’

Integral Expression:

• Which produce integer result after implementing all the automatic (Implicit) and explicit type
conversions. When we want to do calculation of integer values at that time we use Integral
Expression.
For e.g.,
m*n–5 where m and n are integer variables.
FloaExpression:

• After all conversions, produce floating point result. When we want to do calculation of
float values at that time we use Float Expression.
For e.g., x * y / 10 where x and y are floating point variables.
Pointer Expression:
• It produces address values. When we want to use Pointer values at that time we use Pointer
Expression. For e.g.,
&m
ptr + 1 where m is a variable and ptr is a pointer.
Relational Expression:
• It gives results of type bool which takes a value true or false. When we want to do comparison
using relational operator at that time we use Relational Expression.
• For e.g., x<y a==b
• It is also known as Boolean expressions.
Implicit Conversion:
• We can mix data types in expressions. For example:
M=3+2.45;
• In above example it is valid statement. Whenever data types are mixed in an expression,C++
performs the conversions automatically.
• This process is known as Implicit or Automatic conversion.
• The waterfall model shows how the Implicit conversion happens :

short char

Subject : Object Oriented Programming with C++


26
Swami Sahajanand College of Information Technology BCA SEM -3

int

unsigned
long int

unsigned long int

float

double

long double

Logical Expression:
• It combines two or more relational expressions and produces bool type results. When we
want to do compare values using OR, and AND not logical operator at that time we use Logical
Expression. For e.g.,
a > b && x = 10 x = = 10 || y = = 5

• The logical expression given above is true only if both the condition are true. If either or both
of them are false, the expression is false.
Bitwise Expression:

• x << 3 // shift three bit It is used to manipulate data at bit level. They are basically used for
testing or shifting bits. When we want to shift bit position at that time we use bitwise
operator << and >>, and at this time it is not considered as a Insertion and Extraction
operator. For e.g., position to left y >> 1 // shift one bit position to right

• Shift operators are often used for multiplication and division by powers of two.
Simple C++ Program:

#include <iostream.h> //Include Header file for cout and cin objects
int main( ) // Main Function from where execution starts
{
float num1,num2,sum; //Variable Declaration

Subject : Object Oriented Programming with C++


27
Swami Sahajanand College of Information Technology BCA SEM -3

cout<<”Enter Number1”; // Output using insertion operator


<< cin>>num1; // fatch value from user using Extraction
operator >> cout<<”Enter Number2”;
cin>>num2;
sum=num1+num2;
cout<<”Sum =
“<<sum; return 0;
}
Output Operator:

• The identifier cout is a predefined object that represents the standard output stream inC++
and its represents the screen.
• The operator << is called the insertion or put to operator. It inserts or sends the contentsof
the variable on its right to the object on its left.

Input Operator:

• The identifier cin is a predefined object in C++ that corresponds to the standard input
stream.
• The operator >> is known as extraction or get from operator. It extracts the value fromthe
keyboard and assigns it to the variable on its right.

Keyboard cin >> 18

Scope Resolution Operator: Object Extraction Operator Variable

• :: is known as the scope resolution operator has been introduced to access an item that is
outside the current scope.
• This operator is also used for distinguishing class members and defining class methods.
• The same variable name can be used to have different meanings in different blocks.
• The scope of the variable extends from the point of its declaration till the end of the block
containing the declaration.
• A variable declared inside a block is said to be local to that block.
• Declaration :
:: variable-name;

Subject : Object Oriented Programming with C++


28
Swami Sahajanand College of Information Technology BCA SEM -3

• This operator allows access to the global version of a variable.


Example:
#include<iostream.h>
#include<conio.h>
int m=10; // global variable
int main()
{
int m=20;
clrscr();
cout<<”m=”<<m<<endl; cout<<”global m=”<<::m<<endl; getch();
return 0;
O/P→ m=20
global m=10
Memory Management Operators new and delete
• C Language uses malloc( ) and calloc( ) functions to allocate memory dynamically at run time
and free( ) to free dynamically allocated memory.
• We use dynamic allocation techniques when it is not known in advance how much of memory
space is needed.
• C++ also supports this feature with the help of unary operator new and delete that perform the
task of allocating and freeing the memory.
• An object created with new keyword will remain exist until it is destroyed using delete. Thus the
lifetime of an object is directly under our control and is unrelated to the block structure.
• Syntax for new :
pointer – variable = new data-type;
• The pointer variable is a pointer of type data-type. The new operator allocated sufficient
memory to hold a data object of type data and returns the address of the object. The data- type
may be any valid data type.
p = new

int;q = new float;

Where p is pointer of type int and q is pointer of type float.


• We can also initialize value while allocating memory.
Syntax: -data-type pointer–variable = new data-type(value);

Example: - int *p = new int(25);

• We can allocate memory for any data type including user defined variables like union,

Subject : Object Oriented Programming with C++


29
Swami Sahajanand College of Information Technology BCA SEM -3

structures and classes with the help of new keyword. The general form for one- dimensional
array is :
Syntax :- pointer-variable = new data-type[size];

Example :- int *p = new int[25];

• Creating multidimensional array using new :


int *p = new int[3][5][4]; //valid
int *p = new int[3][5][ ]; //invalid
int *p = new int[m][5][4]; //valid

• When data is no longer needed it is destroyed to release the memory space for reuse. The
general form of delete is :
Syntax for delete :- delete pointer-variable;

Example :- delete p;

• The pointer variable is the pointer that points to a data created with new.
• If we want to free a dynamically allocated array, we must use the following form of delete:
delete [size]pointer-variable;
The size specifies the numbers of elements in the array to be freed. delete [ ]p;

This is also valid when there is not sufficient memory new returns NULL pointer.

Advantages of new over malloc( ):

• It automatically computes the size of the data object. We need not use the operator sizeof.
• It automatically returns the correct pointer type, so that there is no need to use a type
cast.
• It is possible to initialize the object while creating the memory space.
• Like any other operator, new and delete can be overloaded.
Manipulators.:

• Manipulators are operators that are used to format the data display. The most commonly
used manipulators are endl and setw.
• The endl manipulator, when used in an output statement, causes a linefeed to be inserted. It
has the same effect as using the newline character “ \n“.

Subject : Object Oriented Programming with C++


30
Swami Sahajanand College of Information Technology BCA SEM -3

• setw is used to display formatted output . If we want to display output as right-justified atthat
time we use setw.
• When we use setw we pass field width value in setw( ). So, it starts display from right to left.

Program:-
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
int main()
{
int basic=950,allowance=95;
cout<<setw(10)<<”Basic”<<setw(10)<<basic<<endl
cout<<setw(10)<<”Allowance”<<setw(10)<<allowance<<endl;
getch();
return 0;
}

O/P→ Basic 950


Allowance 95
• There are two other manipulators in c++ setfill and setprecision.
• Setfill used after setw manipulator. The usage of setfill manipulator is a value does not
entirely filled then the character specified in setfill argument of the manipulator is used to fill
the field.
For example:

#include<iostream.h>
#include<conio.h>
#include<iomanip.h> //Header file for
manipulators Void main()
{
clrscr();
cout<<setw(10)<<setfill(‘$’)<<70<<30<<endl;
getch();
}
O/P: $$$$$$7030
Type Cast Operator (Explicit Conversion):

Subject : Object Oriented Programming with C++


31
Swami Sahajanand College of Information Technology BCA SEM -3

• C++ is permits explicit type conversion of variables or expressions using the type cast
operator.
• The process of such a local conversion is known as explicit conversion or casting a value.
• The Syntax is changed for casting in C++ :
(type-name) expression // C
notation type-name (expression) // C++ notation
• Where type-name is one of the standard data types. The expression may be a constant,
variable or an expression.
• Example :
float average = sum/(float)i; // C notation
float average = sum/float(i); // C++ notation
• Where division is done in floating point mode and value of average is gain the fractional
part of result.
Function (Member Function, Friend Function, Inline Function)
There are Three types of Functions in C++.

1.Member function
2.Inline function
3.Friend function
1.Member Function
• Member functions can be defined in two places:

(1) Outside the class definition.


(2) Inside the class definition.

(1) Outside the class definition:-

• Member functions that are declared inside a class have to be defined separately outsidethe
class.
• Their definitions are very much like the normal functions.
• They should have a function header and a function body.
An important difference between a member function and a normal function is that a member
function incorporates a membership ‘identity label’ in the header.

• Syntax :-
return-type class-name : : function-name(argument declaration)
{

Subject : Object Oriented Programming with C++


32
Swami Sahajanand College of Information Technology BCA SEM -3

function body
}

Example :-
void item :: getdata(int a)
{
number = a;
}
(2) Inside the class definition:-

• Another method of defining a member function is to replace the function declaration bythe
actual function defining inside the class.
Example :-

class item
{
private:
int number; float cost;
public:
void putdata(void) // definition inside the calss
{
cout<<number<<endl;
}
};

(2) Inline Function


• “An inline function is a function that is expanded in line when it is invoked.”
• To eliminate the cost of calls to small functions, C++ proposes a new feature called inline
function.
Syntax :-
inline function-header
{
function body
}
Example:-
Inline int mul(int x,int y)
{ return (x*y); // 20

Subject : Object Oriented Programming with C++


33
Swami Sahajanand College of Information Technology BCA SEM -3

int main( )
{
cout<<mul(5,4); getch();
return 0;
}
O/P→20
Where inline expansion may not work?

• If functions contain static variables.


• If inline functions are recursive.

(3) Friend Function

• When we want to access private data of an particular class at that time we declarefunction
as a friend.
• The functions that are declared with the keyword friend are known as “friend functions”.
• The function declaration should be preceded by the keyword friend.
• It is not a member of any class.
• A function can be declared as a friend in any number of classes.
Program :-

// Friend function in two classes


#include<conio.h>
#include<iostream.h>
class abc; // forward declaration class xyz
{
Int x;
public:
void setvalue(int i)
{
x=I;
}
class abc
};
{

Subject : Object Oriented Programming with C++


34
Swami Sahajanand College of Information Technology BCA SEM -3

friend void max(xyz,abc);


int a;
public:
void setvalue(int i)
{
a=I;
}
friend void max(xyz,abc);
};
void max(xyz m, abc n)
{
if(m.x>=n.a)
cout<<m.x;
else
cout<<n.a;
}
int main()
{
abc a1; a1.setvalue(10); xyz x1; x1.setvalue(20); max(a1,x1);
getch();
return 0;
}
O/P→ 20
Characteristics of friend function

• It is not in the scope of the class to which it has been declared as friend.
• Since it is not in the scope of the class, it cannot be called using the object of that class.
• It can be invoked like a normal function without the help of any object.
• Unlike member functions, it cannot access the member names directly and has to use an
object name and dot membership operator with each member name. (e.g. A.x)
• It can be declared either in the public or the private part of a class without affecting its
meaning.
• Usually, it has the objects as arguments.

Subject : Object Oriented Programming with C++


35
Swami Sahajanand College of Information Technology BCA SEM -3

◆ Input Output statements

• C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device
likes a keyboard, a disk drive, or a network connection etc. to main memory, this is
called input operation and if bytes flow from main memory to a device likes a display
screen, a printer, a disk drive, or a network connection, etc., this is called output
operation.
I/O Library Header Files:

• There are following header files important to C++ programs:

Header File Function and Description

This file defines the cin, cout, cerr and clog objects,
which correspond to the standard input stream, the
standard output stream, the un-buffered standard error
<iostream>
stream and the buffered standard error stream,
respectively.

This file declares services useful for performing


<iomanip> formatted I/O with so-called parameterized stream
manipulators, such as setw and setprecision

Subject : Object Oriented Programming with C++


36
Swami Sahajanand College of Information Technology BCA SEM -3

The standard output stream (cout):

The predefined object cout is an instance of iostream class.

• The cout object is said to be "connected to" the standard output device, which
usually isthe display screen.
• The cout is used in conjunction with the stream insertion operator, which is written as
<<which are two less than signs as shown in the following example.
#include <iostream>
int main( )
{
char str[] = "Hello C++";
cout << "Value of str is : " << str << endl;
}
O/P : Value of str is : Hello C++
The insertion operator << may be used more than once in a single statement as shown above
and endl is used to add a new-line at the end of the line.
The standard input stream (cin):

• The predefined object cin is an instance of istream class. The cin object is said to be
attached to the standard input device, which usually is the keyboard. The cin is used in
conjunction with the stream extraction operator, which is written as >> which are two
greater than signs as shown in the following example.
#include <iostream>
int main( )
{
char name[50];
cout << "Please enter your name: "; cin >>
name;
cout << "Your name is: " << name << endl;
}
O/P: Please enter your name: c plus plus Your name is: c plus plus

Subject : Object Oriented Programming with C++


37
Swami Sahajanand College of Information Technology BCA SEM -3

• The stream extraction operator >> may be used more than once in a single statement.
Torequest more than one datum you can use the following:
cin >> name >> age;
• This will be equivalent to the following two statements:
cin >> name; cin >> age;
Declaration and creation of Classes and Objects

Class:
• When you define a class, you define a blueprint for a data type. This doesn't
actually define any data, but it does define what the class name means, that is, what an
object of the class will consist of and what operations can be performed on such an
object.
• A class definition starts with the keyword class followed by the class name and the
class body, enclosed by a pair of curly braces. A class definition must be followed either
by a semicolon or a list of declarations. For example we defined the Box data type using
the keyword class as follows:
class Box
{
private:
int length,breadth,height; // Length, Breadth & Height of a box
int area; //Area of Box
public:
void getdata(); //Function Declaration
void display() //Function Declaration & Definition Within Class
{
cout<<”Area is : ”<<length*breadth*height;
}
}box1; //creation of object box1

• The keyword public determines the access attributes of the members of the class that
follow 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.

Subject : Object Oriented Programming with C++


38
Swami Sahajanand College of Information Technology BCA SEM -3

Object
• Class provides the blueprints for objects, so basically an object is created from a class.
We declare objects of a class with exactly the same sort of declaration that we declare
variables of basic types. Following statements declare two objects of class Box written
in main()
Box box1; // Declare box1 of type
Box Box box2; // Declare box2 of
type Box
• Both of the objects Box1 and Box2 will have their own copy of data members.
• You can create object in two ways either at the end of class definition or in the
main()function.

Subject : Object Oriented Programming with C++


39
Swami Sahajanand College of Information Technology BCA SEM -3

UNIT - 2

Subject : Object Oriented Programming with C++


40
Swami Sahajanand College of Information Technology BCA SEM -3

Constructor, Operator overloading and Type conversion

CONSTRUCTOR-AN INTRODUCTION: -
Main goal of creating class to make user defined data type, which is similar to build -
in- data-type. We know that we can initialize the built-in-data-type variable during
declaration. But we cannot initialize the class object during declaration in this way.

Int a = 20; // Simple built-in-data-type variable. Allow


student s=30; // Not allow. Student is class object

To initialize our class object during creating (declaration) we are using special
member function known as constructor. The name of this member function is same as
your class name. This function is called when we create object. It is known as
constructor because it constructs the value of the variable inside the class.
Constructor has following characteristics:
• It should be declared in public section.
• It is invoked (called) when object is created.
• It does not have any return type, not even void. So it doesn’t return value.
• It cannot be inherited but child class can call parent class constructor.
• Constructors cannot be virtual.
• We cannot refer to its address.
• An object with a constructor cannot be used as a member of union.

Consider the following class ‘Rectangle’ in which we are initializing member of class
‘length’ and ‘width’ during creating object.
Class Rectangle
{
int length;
int width;
public :
Rectangle(void); // Declaration of constructor function
}
Rectangle :: Rectangle(void)

Subject : Object Oriented Programming with C++


41
Swami Sahajanand College of Information Technology BCA SEM -3

{ // Definition of constructor function


length = 0;
width = 0;
}
void main( )
{
Rectangle r1; // Automatically initialize the value of length and width
}
In above class we have constructor function name ‘Rectangle’. We are passing no any
argument into this function. In the definition of function we initialize length and width
equal to zero. This function is automatically called when we are creating object.
A constructor do not accepts any argument (parameter) is known as default constructor.

In above example our constructor ‘Rectangle’ has no any argument so it is known


as the default constructor.
PARAMETERIZED CONSTRUCTOR: -
In default constructor we can initialize all object variable by fixed value. But sometimes it is
necessary to initialize the all object variable with different value. For that we have to use
parameterized constructor.
“A constructor function which receives argument is called parameterized constructor.”
e.g. Consider the following class ‘Rectangle’ in which we are initializing member
of class ‘length’ and ‘width’ with different value for each object.

class Rectangle
{
int length;
int width;
public :
Rectangle(int, int); // Declaration of constructor function
}
Rectangle :: Rectangle(int l, int w)
{ // Definition of constructor function length = l;
width = w;
}
We can pass argument to the constructor function during creating object by two ways:

Subject : Object Oriented Programming with C++


42
Swami Sahajanand College of Information Technology BCA SEM -3

By calling the constructor explicitly:


e.g. Rectangle r1 = Rectangle(20, 30);

Here we are passing 20 and 30 which received as ‘l’ and ‘w’ in constructor.

By calling constructor implicitly: This method is also known as shortcut method. It


is easy to write and read.
e.g. Rectangle r2(20, 30);
So the main function for the above class is:void main( )
{
Rectangle r1=Rectangle(20,30); //
Explicit call Rectangle
r2(20,30); // Implicit call
………
}
When we are passing argument (parameter) to the constructor function it is
known as the parameterized constructor.
COPY CONSTRUCTOR: -
We can pass any variable (either primary data type, array, structure or class object) as
argument in function but we cannot pass the same class object as argument. But we can
pass the reference of the same class object as argument. This is known as copy constructor.
“In constructor when reference to the same class object is passed as argument then it is
called as copy constructor.” e.g. Consider the following class ‘Rectangle’ in which we are
initializing member of class ‘length’ and ‘width’ by passing reference of class ‘Rectangle’.
class Rectangle
{
int length;
int width;
public:
Rectangle(Rectangle &); // Declaration of constructor function
}
Rectangle :: Rectangle(Rectangle &o)
{ // Definition of constructor function length =o.length;

Subject : Object Oriented Programming with C++


43
Swami Sahajanand College of Information Technology BCA SEM -3

width = o.width; }
We can initialize the copy constructor by three ways:
By calling the constructor explicitly:
e.g. Rectangle r2 = Rectangle(r1);
By calling constructor implicitly:
This method is also known as shortcut method. It is easy to write and read.
e.g. Rectangle r2(r1);

Copy Initialization: “The way of initialization of object using copy constructor


in form ofclassname object1 = object2
is known as copy initialization”
Rectangle r2 = r1; // Copy initialization
MULTIPLE CONSTRUCTOR IN CLASS (CONSTRUCTOR OVERLOADING): -
As the other normal function we can also overload the constructor. e.g. Consider the
following class ‘Rectangle’ in which we are using multiple constructor
class Rectangle
{
int length;
int width;
public:
Rectangle( ) ; // default constructor
Rectangle(int, int); // Parameterized constructor
Rectangle(Rectangle &); // Copy constructor
};
Rectangle :: Rectangle( )
{
length = 0;
width = 0;
}
Rectangle :: Rectangle(int l, int w)
{
length = l; width = w;

Subject : Object Oriented Programming with C++


44
Swami Sahajanand College of Information Technology BCA SEM -3

}
Rectangle :: Rectangle(Rectangle &o)
{
length = o.length; width = o.width;}

// main function
Void main()
{
Rectangle r1; // Call default constructor
Rectangle r2(20, 30); // Call parameterized constructor
Rectangle r3 = r2; // Call copy constructor
}
In above example we are using three different constructor functions in class. First
constructor is default constructor and has no argument. Second constructor is
parameterized constructor and has two integer arguments. Third constructor is copy
constructor and it is using the reference of same class object as argument. Also as shown in
the main function we can call first constructor by simply creating object.
Rectangle r1;
We can call second constructor by passing argument during object creation. Rectangle
r2(20, 30);
We can call third constructor by copy initialization method. Also we can call by passing
argument of object of type rectangle.
Rectangle r3 = r2;
CONSTRUCTOR WITH DEFAULT ARGUMENT: -
Similar to other normal function we can also define the constructor with default argument.
Consider the following program in which we have used default argument for the
constructor.
class Rectangle
{
int length;
int width;
public:

Subject : Object Oriented Programming with C++


45
Swami Sahajanand College of Information Technology BCA SEM -3

Rectangle(int l, int w=0); // w is default argument


};
Rectangle :: Rectangle(int l, int w)
{
length = l;
width=w;}
// main function
void main( )
{
// Call parameterized constructor without using default argument
Rectangle r1(20, 30);
// Call parameterized constructor with using default argument
Rectangle r2(30);
}
Here in above program we have used ‘w’ as default argument. So when we are passing
two arguments then this default argument will not be used. But when we are passing
only one argument then this default argument will be used.
Destructors
• A destructor is used to destroy the objects that have been created by a constructor.
• Like a constructor, the destructor is member function whose name is the same as
theclass name but is preceded by a tilde (~).
e.g.
~ integer()
{
}
• A destructor never takes any arguments nor does it return any value.
• It will be called implicitly by the compiler upon exit from the program to
clean upstorage that is no longer accessible.
• It is a good practice to declare destructors in a program since it releases memory
spacefor future use.
• Whenever new is used to allocate memory in the constructors, we should use

Subject : Object Oriented Programming with C++


46
Swami Sahajanand College of Information Technology BCA SEM -3

delete tofree that memory.

Basic of Operator Overloading:

C++ provides the facility to use operator with user-defined data type just like basic
data type. C++ provides the special meaning to the operator. By operator overloading
we can provide the new definition to operator. It is known as the operator overloading.
“Operator overloading is a technique to give special meaning to an operator.” We can
overload all C++ operator but we cannot overload following operator.
1. Class member access operator ( . and .* )
2. Scope resolution operator ( :: )
3. Size operator ( sizeof )
4. Conditional operator ( ?: )
We cannot change the precedence or associatively of operator by operator overloading.

e.g. Multiplication operator has higher precedence than addition operator. We cannot
change this meaning.
How to overload operator:

To perform operator overloading we are using special operator function.


The format of operator function is:
returntype operator op(argument1, argument2, …);
where op = operator to be overload
In above case the function name is ‘operator op’.
Operator function is either member function of class or friend function. A friend function has
only one argument for unary operation and two arguments for binary operation. A member
function has no argument for unary operator and one argument for binary operation.

Operator function can be called by following two ways:


Simple method just like normal function:
This method is similar to call function which we are using for the other normal
function.For unary operation we can call the operator function by:
objectname.operator op(operand); //where op=operator
For binary operation we can call the operator function by:
objectname.operator op(operand1, operand2);

Subject : Object Oriented Programming with C++


47
Swami Sahajanand College of Information Technology BCA SEM -3

Called just like expression:


This method is just like the normal expression which we are using for various operation
such as addition, subtraction, multiplication, etc. (e.g. a + b)

For unary operation we can call the operator function.

op operand // here op = operator

or
operand op
For binary operation we can call the operator function by:

operand1 op operator2

OVERLOADING UNARY OPERATORS USING MEMBER FUNCTION:


In unary operation there is only one operator and one operand. In minus operation when
we place minus before any operand then sign of that operand will be changed. We can
apply this unary minus operation to object by using operator overloading. We can
implement this by using friend function or member function.
Here we have overloaded unary operator using member function. In this example we are
using one class ‘space’ which has three data members ‘x’, ‘y’, and ‘z’. We are changing the
sign of these data member by using overloaded minus operator. In this example we are not
passing any argument to the operator function.

class space
{
private:
int x,y,z;
public:
void getdata(int ,int ,int);void display();
void operator -();
};
void space :: getdata(int a, int b, int c)
{

Subject : Object Oriented Programming with C++


48
Swami Sahajanand College of Information Technology BCA SEM -3

x=a; y=b; z=c;


}
void space :: display()
{
cout<<"A = "<<x<<endl; cout<<"B = "<<y<<endl; cout<<"C = "<<z<<endl;
}
// member operator function definition void space :: operator-()
{
x=-x;
y=-y;
z=-z;
}
int main()
{
space m; m.getdata(10,-20,30); m.display();
-m; m.display(); return 0;
}
OVERLOADING BINARY OPERATORS USING MEMBER FUNCTION: -

We can overload the binary operator as like as the unary operator either using member
function or friend function. If we are using member function then we have to pass only
one argument to the operator function. If we are using friend function to overload binary
operator then we have to pass two arguments to operator function.

Consider the example of class ‘Rectangle’ in which we are overloading operator ‘+’ to add
the two objects of ‘Rectangle’ class and create new object which has sum of length and
width of both previously created object. Here we are using member function to overload
the operator.
class Rectangle
{
int length; int width; int area;

public :
Rectangle operator+(Rectangle); // Overloading + operator
};
// Definition for operator function

Subject : Object Oriented Programming with C++


49
Swami Sahajanand College of Information Technology BCA SEM -3

Rectangle Rectangle :: operator+(Rectangle r)


{
Rectangle tmp;
tmp.length = length + r.length; tmp.width = width + r.width; return(tmp);
}
void main()
{
Rectangle r1,r2,r3;

// Call operator overload function + (This method is called by the object r1)
r3 = r1 + r2;
}
In above example we have used member function to overload ‘+’ operator. We have to note
following points in above example:
An Operator function ‘operator +’ has one argument of object of class ‘Rectangle’. An
Operator function returns the object of type ‘Rectangle’.
It is a member function of class ‘Rectangle’.
We can call the operator function by using following statement: r3 = r1 + r2;
Here object ‘r1’ call the function ‘operator +’ and ‘r2’ object is passed as argument. The
operator function returns the object and assigned to object ‘r3’.
r3 = r2 + r1 ;
In above statement, ‘r2’ object calls the function ‘operator +’ and ‘r1’ object is passed as
argument.
So in short we can say in operator overloading, in expression, left operator takes the
responsibility to invoke the operator function and right operator is passed as an argument.
We can call the operator function also by following function call.
r3 = r1.opeator + ( r2); or
C3=c1+c2

class Complex
{
float x; float y; public:
Complex()

Subject : Object Oriented Programming with C++


50
Swami Sahajanand College of Information Technology BCA SEM -3

{
}
Complex(float real, float imag)
{
x = real; y = imag;
}
Complex
operator+(Complex);
void display(void);
};

Complex Complex :: operator+(Complex c)


{
Complex temp; temp.x = x + c.x; temp.y = y + c.y; return(temp);
}
void Complex :: display(void)
{

cout<< x <<" "<< y << "\n";


}
int main()
{
Complex c1,c2,c3;
c1 = Complex(2 ,3);
c2 = Complex(5 ,2);
c3 = c1 + c2;
cout<< " c1 = "; c1.display();
cout<< " c2 = "; c2.display();
cout<< " c3 = "; c3.display();
return 0;
}

Subject : Object Oriented Programming with C++


51
Swami Sahajanand College of Information Technology BCA SEM -3

OVERLOADING UNARY OPERATORS USING FRIEND FUNCTION:

In unary operation there is only one operator and one operand. In minus operation when
we place minus before any operand then sign of that operand will be changed. We can
apply this unary minus operation to object by using operator overloading. We can
implement this by using friend function or member function.
class space
{
private:
int x; float y;
public:
void getdata(int ,float); void display();
friend void operator -(space &s1); /*declaration of operator overloading */
};

void space::getdata(int a,float b)


{
x=a; y=b;
}
void space::display()
{
cout<<endl<<"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"<<endl;cout<<" The value of
X="<<x<<endl; cout<<"The value of Y="<<y<<endl;
}
void operator -(space &s1) /* defination of function */
{
s1.x = s1.x - 2;
s1.y = s1.y - 2;
}
int main()
{
int intdata,floatdata;

Subject : Object Oriented Programming with C++


52
Swami Sahajanand College of Information Technology BCA SEM -3

cout<<endl<<"Enter integer data :- ";


cin>>intdata;
cout<<endl<<"Enter float data :- ";
cin>>floatdata;
space s;
s.getdata(intdata,floatdata);
cout<<"Object display"<<endl;
s.display();
-s; //implicit call
cout<<"object S overloaded by unary operator.. using first method"<<endl;
s.display();
cout<<"Object S overloaded by unary operator second time"<<endl;
operator -(s); //explicit call
s.display();
return 0;
}

In above program we are passing reference to the object. We cannot pass simple object
because when we change the value in called function there will not be change in calling
function so to make change in calling function we are using reference to object.
OVERLOADING BINARY OPERATORS USING FRIEND FUNCTION:
We can overload the binary operator as like as the unary operator either using member
function or friend function. If we are using member function then we have to pass only one
argument to the operator function. If we are using friend function to overload binary operator
then we have to pass two arguments to operator function.
Consider the example of class ‘Rectangle’ in which we are overloading operator ‘+’ to add the
two objects of ‘Rectangle’ class and create new object which has sum of length and width of
both previously created object.
class Rectangle
{
int length; int width; int area;
public :

Subject : Object Oriented Programming with C++


53
Swami Sahajanand College of Information Technology BCA SEM -3

// overloading + operator using friend function friend Rectangle operator+(Rectangle,


Rectangle);
};
// Definition of operator function
Rectangle operator+(Rectangle r1, Rectangle r2)
{
Rectangle tmp;
tmp.length = r1.length + r2.length; tmp.width = r1.width + r2.width; return(tmp);
}
void main()
{
Rectangle r1,r2,r3;
// Call operator overload function + (We are using friend function)
r3 = r1 + r2;
}

In above example we have used friend function to overload ‘+’ operator. We have to note
following points in above example:
An Operator function ‘operator +’ has two arguments of object of class ‘Rectangle’. An
Operator function returns the object of type ‘Rectangle’. It is a friend function.

We can call the operator function by using following statement:


r3 = r1 + r2;

Here we are directly calling operator function and passing two objects of class ‘Rectangle’ as
arguments (one is ‘r1’ and another is ‘r2’). The operator function returns the object and
assigned to object ‘r3’.

We can call the operator function also by following function call. r3 = operator + (r1, r2);
class student
{
int sub1;

Subject : Object Oriented Programming with C++


54
Swami Sahajanand College of Information Technology BCA SEM -3

int sub2;
int total;
int avg;
public:
student()
{
}
student(int a,int b)
{
sub1=a; sub2=b;
}
void display()
{
cout<<endl<<"therory:- "<<sub1; cout<<endl<<"practical:- "<<sub2;
}
friend student operator +(student,student);
};

student operator +(student a2,student a3)


{
student a4; a4.total=a2.sub1+a3.sub2;
a4.avg=a4.total/8;
cout<<endl<<"total:- "<<a4.total;
cout<<endl<<"average :- "<<a4.avg;
return a4;
}
int main()
{
student a1,a2,a3; a1=student(540,60);a2=student(620,72);
cout<<endl<<"1st student marks "<<endl;
cout<<endl<<"**************************************";a1.display();
cout<<endl<<"2nd student marks ";
cout<<endl<<"**************************************";
a2.display();

Subject : Object Oriented Programming with C++


55
Swami Sahajanand College of Information Technology BCA SEM -3

cout<<endl<<"1st student total & perecentage :-


"<<endl;a3=a1+a1;
cout<<"\n2nd student total & percentage :-
"<<endl;a3=a2+a2;
return 0;
}
ADVANTAGE OF FRIEND FUNCTION OVER MEMBER FUNCTION: -
We can call the operator function either by friend function or member function. When we are
using member function to overload binary operators at the left hand side there must be object
of class in which the operator function has defined.
Consider the case of operator overloading in which one operand is object type, which method
we have to call for overloading, and another operand is primary data type. Then the expression
for calling operator function:
returnobject= callobject + primarydatatypevariable;
In above expression the object variable is always left hand side. We cannot place primary data
type variable at the left hand side.
Returnobject = primarydatatypevariable + callobject; // illegal
But above expression is allow if we are using friend function. During implementing friend
function we are using function overloading to write the definition about the operator function.
In one operator function we are first passing object variable and then passing primary data
type variable. So when we are using above first method to call operator function then this
function is called.
In second operator function we are first passing primary data type variable and then passing
object variable. So when we are using above second method to call operator function then this
function is called.
class Rectangle
{
int length; int width; int area;
public :
void read();

Subject : Object Oriented Programming with C++


56
Swami Sahajanand College of Information Technology BCA SEM -3

void print();
// Function overloading for operator function
friend Rectangle operator+(Rectangle, int);
friend Rectangle operator+(int, Rectangle);
};
void Rectangle :: read()
{
clrscr();
cout << "Enter the length of Rectangle : "; cin >> length;
cout << "Enter the width of Rectangle : "; cin >> width;
}
void Rectangle :: print()
{
cout << endl << endl;
cout << "The length of Rectangle = " << length << endl;
cout << "The width of Rectangle = " << width << endl;
area = length * width;
cout << "The area of Rectangle = " << area << endl;
getch();
}
Rectangle operator + (Rectangle r, int a)
{
Rectangle tmp; tmp.length = r.length + a; tmp.width = r.width + a; return (tmp);
}
Rectangle operator + (int a, Rectangle r)
{
Rectangle tmp; tmp.length = r.length + a; tmp.width = r.width + a; return (tmp);
}

Subject : Object Oriented Programming with C++


57
Swami Sahajanand College of Information Technology BCA SEM -3

void main()
{
Rectangle r1,r2,r3; r1.read();
// Below both forms are valid by function overloading r2=r1 + 5;
r3=10 + r1;
r1.print();
r2.print();
r3.print();
}
OVERLOADING OPERATOR FOR STRING VARIABLE: -
We know that we can create string either by array of character or by character type pointer. To
perform any operation on string (coping string from one string to another, joining two strings,
comparing string) we have to first find out the length of string and we have to perform
operation character by character. Also we can use special string function to perform operation
on it but we cannot use over simple operators to perform operations on string.
In C++ we can overload different operator to perform string operation as like as other number
variable.
Consider following class ‘String’ in which we are overloading + operator for joining two string
into another one.
#include <iostream>
#include<string.h>
using namespace std;
class string1
{
char str[100];
int len;
public :
void read(); // Read the string
void print(); // print string

Subject : Object Oriented Programming with C++


58
Swami Sahajanand College of Information Technology BCA SEM -3

// Declaration for overloading addition operator to joint two string


string1 operator + (string1);
// Declaration for overloading equal to operator for equality of two string
int operator == (string1);
};
// Function to read the data about string
void string1 :: read()
{
cout << "Enter your string : ";
cin >> str;
len=strlen(str);
}
// Function to print the string data
void string1:: print()
{
cout << "Your string = " << str << endl;
}
// Definition for assignment operator function
string1 string1 :: operator+(string1 s)
{
string1 t;
strcpy(t.str,str);
strcat(t.str,s.str);
t.len=len+s.len;
return(t);
}
int string1 :: operator == (string1 s) // Definition for equal to operator
{

Subject : Object Oriented Programming with C++


59
Swami Sahajanand College of Information Technology BCA SEM -3

if (strcmp(str,s.str)==0)
return(1);
else
}
return(0);
int main()
{
//clrscr();
string1 s1,s2,s3;
s1.read();
s2.read();
// Call operator function to join two
string s3=s1 + s2;
// Call operator function to compare two string
if(s1 == s2)
cout<<"Both string are same";
else
cout<<"Both are not same";
// Print joined string
s3.print(); return 0;
}
Similarly we can overload the operator to compare two strings. For that we have to overload
different relational operator = = , <=, >=, !=, < , >. Also we can overload assignment operator
(=) to copy one string into another but there is not necessity to overload the assignment
operator because object can directly assign to another object without overloading.
RULES FOR OVERLODGIN OPERATOR: -
Following are rules to overload operator:
Only existing operator in C++ can be overloaded. We cannot create our new operator for
overloading.
The overloaded must have at lease one operand that is user-defined type.
Overloaded operator follows the same rules apply to original operator. For example the
precedence of * operator is higher than + operator so during operator overloading same rules
apply to these operators.

Subject : Object Oriented Programming with C++


60
Swami Sahajanand College of Information Technology BCA SEM -3

We cannot overload following operators.


Operator Sign Operator Name
. Membership Operator
.* Pointer to member operator
:: Scope resolution operator
?: Conditional operator
Sizeof Size of operator

We cannot use friend function to overload following operators but we can use only
memberfunction.
Operator Sign Operator Name

= Assignment operator

() Function call operator

[] Subscript or index operator

-> Class member access operator

• When we are overloading unary operator by using the friend function we have to pass
one argument.
• When we are overloading unary operator by using the member function we are not
passing any argument to the operator function.
• When we are overloading binary operator by using the friend function we are passing
two arguments.
• When we are overloading binary operator by using the member function we are passing
only one argument.
• Binary arithmetic operators such as +, -, *, and / must return a value.

Subject : Object Oriented Programming with C++


61
Swami Sahajanand College of Information Technology BCA SEM -3

UNIT - 3
Subject : Object Oriented Programming with C++
62
Swami Sahajanand College of Information Technology BCA SEM -3

◆ Inheritance
• “Inheritance is a process by which object of one class acquires properties of object of
another
class.”
•“
Inheritan
ce is a
concept
of
reusabilit
y.”
“The
mechanis
Base m of
class deriving a
new class from an old class is called inheritance or derivation.”
Example :-

Derived
class
Subject : Object Oriented Programming with C++
63
Swami Sahajanand College of Information Technology BCA SEM -3

• Visibility of inherited members :

Derived class visibility


Base class visibility Types of inheritance supported by C++

Public derivation Private derivation Protected derivation

private → Not inherited Not inherited Not inherited

protected → Protected Private Protected

public → Public Private Protected

Single Level Inheritance


• “A derived class with only one base class is called single Level inheritance.”
• A derived class can be defined by specifying its relationship with the base class in
addition to its own details.
Syntax :-
class derived-class-name : visibility-mode base-class-name
{
…………………//
………………..// members of derived class
……………..//
};
• The colon indicates that the derived-class-name is derived from the base-class-name.

Subject : Object Oriented Programming with C++


64
Swami Sahajanand College of Information Technology BCA SEM -3

• The visibility-mode is optional and, if present, may be either private or public.


• The default visibility-mode is private.
• Visibility mode specifies whether the features of the base class are privately derived or
publicly derived.

Examples:-
class D : private B //private derivation
{
Members of D
};
class D : public B //public derivation
{
Members of D
};
class D : B //private derivation by default
{
Members of D
};
Program for Single level inheritance
#include<iostream.h>
#include<conio.h>
class Base
{
public:
int a,b;
void get_ab();

Subject : Object Oriented Programming with C++


65
Swami Sahajanand College of Information Technology BCA SEM -3

};
class Derived : public Base // public derivation
{
private:
int c; public:
void mul();
void display();
};
void Base::get_ab()
{
cout<<"Enter value of a : "<<endl;
cin>>a; //10
cout<<"Enter value of b : "<<endl;
cin>>b; //5
}
void Derived::mul()
{
c=b*a; //50
}
void Derived::display()
{
cout<<"a= "<<a<<endl;
cout<<"b= "<<b<<endl;
cout<<"c= "<<c<<endl;
}
int main()
{
clrscr();
Derived d;
d.get_ab(); O/P→
d.mul(); Enter value of a : 10
d.display(); Enter value of b : 5

Subject : Object Oriented Programming with C++


66
Swami Sahajanand College of Information Technology BCA SEM -3

getch(); a= 10
return 0; b= 5
} c= 50
Multiple Inheritance
• “One derived class from several base classes is called Multiple Inheritance.”
• Multiple inheritance allows us to combine the features of several existing classes as a
starting point for defining new classes.

The syntax of a derived class with multiple base classes is as follows:


class D : visibility B1,visibility B2….
{
//body of class D
};
Where visibility may be either public or private. The base classes are separated by commas.

Program for Multiple Inheritance


#include<conio.h>
#include<iostream.h>
class base1 // definition of first base class
{
protected: /* visibility mode is protected */
int m;
public:

Subject : Object Oriented Programming with C++


67
Swami Sahajanand College of Information Technology BCA SEM -3

void get_m(int x)
{
m=x;
}
};
class base2 // definition of second base class
{
protected: // visibility mode is protected
int n;
public:
void get_n(int y)
{
n=y;
}
};
/* definition of Derived class */
class derived : public base1, public base2
{
public:
void display()
{
cout<<"m = "<<m<<endl;
cout<<"n = "<<n<<endl;
cout<<"m*n = "<<m*n<<endl;
}
};
int main()
{
derived d;
clrscr();
d.get_m(10); O/P→
d.get_n(5); m=10

Subject : Object Oriented Programming with C++


68
Swami Sahajanand College of Information Technology BCA SEM -3

d.display(); n=5
getch(); m*n= 50
return 0;
}
Multilevel inheritance
• “A class is derived from another derived class is known as multilevel inheritance.”
• The class B is known as Base class and B1 is known as intermediate base class and
Class D is derived class.

A derived class with multilevel inheritance is declared as follows:


Class B
{
……….
}; //base class
Class B1 : public B
{
……….
}; //B1 derived from B
Class D : public B1
{
………..
}; //D derived from B1

Program for Multilevel Inheritance

#include<iostream.h>
#include<conio.h>
class student // Base class

Subject : Object Oriented Programming with C++


69
Swami Sahajanand College of Information Technology BCA SEM -3

{
protected: /* visibility mode of data is protected */
int rollno;
public:
void getno(void)
{
cout<<endl<<"Enter roll number for student :- "
cin>>rollno;
}
void showno(void)
{
cout<<endl<<"Rollno of student is :- "<<rollno;
}
};

/* defination of intermediate class */


class test : public student // first level inheritance
{
protected:
int
sub1;
int
sub2;
public:
void getmark(void)
{
cout<<endl<<"enter marks for 1st subject :- ";
cin>>sub1;
cout<<endl<<"enter marks for 2nd subject :- ";
cin>>sub2;
}
void putmark(void)
{

Subject : Object Oriented Programming with C++


70
Swami Sahajanand College of Information Technology BCA SEM -3

cout<<endl<<"marks for 1st subject :- "<<sub1;


cout<<endl<<"marks for for 2nd subject :- "<<sub2;
}
};
/* defination of leaf class */
class result : public test // second level inheritance
{
int
total,avg;
public:
void display(void)
{
total=sub1+sub2; // accessing protected member of
base class avg=total/2;
cout<<endl;
showno(); /* member function of class student */
putmark(); /* member function of class test */
cout<<endl<<"total is :- "<<total;
cout<<endl<<"average is :- "<<avg;
}
};
int main()
{
clrscr();
result student1; /* object of result type is declared */
student1.getno(); /* member function of class student */
student1.getmark(); /* member function of class test */
student1.display(); /* member function of class result */
getch();
return 0;
}
O/P→

Subject : Object Oriented Programming with C++


71
Swami Sahajanand College of Information Technology BCA SEM -3

Enter roll number for student :- 1


enter marks for 1st subject :- 80
enter marks for 2nd subject :- 90
Rollno of student is :-1
marks for 1st subject :- 80
marks for 2nd subject :- 90
total is :-170
average is :- 85

Hierarchical Inheritance
• “One class may be inherited by more than one class, this process is known as
Hierarchical Inheritance.”
• The base class will include all the features that are common to the subclasses.
• A subclass can be constructed by inheriting the properties of the base class.
• A subclass can serve as a base class for the lower level classes and so on.

Subject : Object Oriented Programming with C++


72
Swami Sahajanand College of Information Technology BCA SEM -3

Program for Hierarchical Inheritance


#include<iostream.h>
#include<conio.h>
#include<string.h>
class media /* base class */
{
protected:
char title[20];
float price;
public:
media(char *ptr,float p) /* parameterized constructor */
{
//cout<<endl<<"media class constructor called";
strcpy(title,ptr);
price=p;
}
};
class CD : public media /* first derived class*/
{
private:
char c_type[15];
int qty;
public:
CD(char *ptr,float p,char *c,int q):media(ptr,p)
{
//cout<<endl<<"CD constructor called";
strcpy(c_type,c);
qty=q;
}
void display();
};

Subject : Object Oriented Programming with C++


73
Swami Sahajanand College of Information Technology BCA SEM -3

void CD::display()
{
cout<<"\nTitle : "<<title;
cout<<"\nCD Type: "<<c_type;
cout<<"\nPrice : "<<price;
cout<<"\nQuantity : "<<qty;
cout<<"\nAmount : Rs. "<<qty*price;
}
class Flopy : public media /* second drived class */
{
private:
char f_type[15]; int qty;
public:
Flopy(char *ptr,float p,char *c,int q):media(ptr,p)
{
// cout<<endl<<"floppy constructor called";
strcpy(f_type,c);
qty=q;

}
void display();
};
void Flopy::display()
{
cout<<"\nTitle :"<<title;
cout<<"\nFlopy Type: "<<f_type;
cout<<"\nPrice : "<<price;
cout<<"\nQuantity : "<<qty;
cout<<"\nAmount :Rs. "<<qty*price;
}
int main()
{
clrscr();
CD cd1("Samsung",10.00,"700MB/80 MIN",5);
Flopy fl1("Sony",12.00,"1.44MB",5);
cout<<endl<<"...Cd Detail..."<<endl;
cd1.display();

Subject : Object Oriented Programming with C++ 74


Swami Sahajanand College of Information Technology BCA SEM -3

cout<<endl<<endl<<"...Flopy Detail..."<<endl;
fl1.display();
getch();
return 0;
}
O/P
… Cd Detail …

Title : Samsung
Cd Type : 700MB / 80 MIN
Price : 10
Quantity : 5
Amount : Rs. 50

… Flopy Detail
… Title : Sony
Flopy Type : 144 MB
Price : 12
Quantity : 5
Amount : Rs. 60

Virtual Base Class


• When a class is made a virtual base class, c++ takes necessary care to see
that only one copy of that class is inherited, regardless of how many inheritance
paths exist between the virtual base class and a derived class.
• Consider a situation where all the three kinds of inheritance, namely, multilevel,
multiple and hierarchical inheritance, are invoked.
• This is illustrated in below. The ‘child’ has two direct base classes ‘parent1’ and
‘parent2’ which themselves have a common base class ‘grandparent’. The
‘child’ inherits the traits of ‘grandparent’ via two separate paths.
• It can also inherit directly as shown by the broken line. The ‘grandparent’ is
sometimes referred to as indirect base class.
• All public and protected members of ‘grandparent’ are inherited into ‘child’
twice, first via ‘parent1’ and again via ‘parent2’.
• This means,’ child’ would have duplicate sets of the members inherited from
‘grandparent’.
• This introduces ambiguity and should be avoided.
Subject : Object Oriented Programming with C++ 75
Swami Sahajanand College of Information Technology BCA SEM -3

The duplication of inherited members due to these multiple paths can be avoided by
making the common base class as virtual base class while declaring the direct or
intermediate base classes which is shown as follow:

class A //grandparent
{
…………………..
…………………..
};
Class B1:virtual public A//parent1
{
………………………
……………………….
};
Class B2:public virtual A//parent2
{
…………………………..
…………………………..
};
Class C : public B1 ,public b2 //child
{
…………………..//only one copyA
……………………//will be inherited
};

Subject : Object Oriented Programming with C++ 76


Swami Sahajanand College of Information Technology BCA SEM -3

Hybrid Inheritance
• “Collection of more than one inheritance is called hybrid inheritance.”
• In below diagram, Combination of Hierarchical inheritance and Multiple
inheritance is shown:
1) From Base class B to Derived classes D1 & D2 --> Hierarchical Inheritance.
2) From class D1 & D2 another derived class D3 Multiple Inheritance.

Program for Hybrid inheritance using virtual base class so only one copy
derived from base class:
#include<conio.h>
#include<iostream.h>
class student
{
protected:
int rollno;
public:
void getno(int a)
{
rollno=a;
}
void putno()
{
cout<<"Roll No = "<<rollno<<endl;
}
};
class test : virtual public student
{

protected:
Subject : Object Oriented Programming with C++ 77
Swami Sahajanand College of Information Technology BCA SEM -3

int sub1,sub2;
public:
void getmark(int x,int y)
{
sub1=x;
sub2=y;
}
void putmark()
{
cout<<"Sub1 = "<<sub1<<endl;
cout<<"Sub2 = "<<sub2<<endl;
}
};
class sports : virtual public student
{
protected:
int score;
public:
void getscore(int s)
{
score=s;
}
void putscore()
{
cout<<"Sports Mark = "<<score<<endl;
}
};
class result : public test, public sports
{
int total,per;
public:
void display()
{
total=sub1+sub2+score; per=total/3;
putno();
putmark();
putscore();
Subject : Object Oriented Programming with C++ 78
Swami Sahajanand College of Information Technology BCA SEM -3

cout<<"Total Score : "<<total<<endl;


cout<<"Percentage : "<<per<<endl;
}
};
int main()
{
clrscr();
result r;
r.getno(10); O/P
r.getmark(60,70); Roll No = 10
r.getscore(80); Sub1 = 60
r.display(); Sub2 = 70
getch(); Sports Mark = 80
return 0; Total Score : 210
} Percentage : 70
Abstract Classes
• “An abstract class is one that is not used to create objects. “
• An abstract class is designed only to act as a base class.
• It is a design concept in program development and provides a base upon
which other classes may be built.
• In the previous example, the student class in an abstract class since it was
not used to create any objects.
Nesting of Classes
• “Creation of an object that contains another object is known as nesting of
classes.”
• It is very different than the creation of an independent object.
• An independent object is created by its constructor when it is declared with
arguments.
• On the other hand, a nested object is created in two stages.
• First, the member objects are created using their respective constructors
and then the other ‘ordinary’ members are created.
• This means, constructors of all the member objects should be called before
its own constructor body is executed.
• This is accomplished using an initialization list in the constructor of the
nested class.
Subject : Object Oriented Programming with C++ 79
Swami Sahajanand College of Information Technology BCA SEM -3

Example:-
class gamma
{
……………
alpha a;//a is object of alpha beta b;// b is object of beta
public:
gamma(arglist): a(arglist1),b(arglist2)
{
// constructor body
}
};
• arglist is the list of argument that is to be supplied when a gamma.
• arglist1 is the argument list for the constructor of a and arglist2 is the
argument list for the constructor of b. arglist1 and arglist2 may or may not
use the arguments from arglist.

Subject : Object Oriented Programming with C++ 80


Swami Sahajanand College of Information Technology BCA SEM -3

UNIT - 4

Subject : Object Oriented Programming with C++ 81


Swami Sahajanand College of Information Technology BCA SEM -3

Polymorphism:

The word polymorphism means having many forms. Typically,


polymorphism occurs when there is a hierarchy of classes and they are
related by inheritance.
C++ polymorphism means that a call to a member function will cause a
different function to be executed depending on the type of object that
invokes the function.
Polymorphism is also one of the main features of object oriented
programming. Polymorphism means ‘one name, many forms’. In C++, there
are static polymorphism and dynamic polymorphism. Function overloading
and operator overloading are examples of static polymorphism and function
overriding is an example of dynamic polymorphism.
Types of Polymorphism:

Static polymorphism / Compile time polymorphism/ static binding/ static


linking:
• Function overloading
• Operator overloading

Dynamic polymorphism/ Run time polymorphism/ dynamic binding/ dynamic


linking:
• Virtual Functions
Using a single function name to handle different numbers and different types of
arguments to perform different types of tasks is known as function overloading.
Example:
class rectangle
{
private:
int length;
int width;
int area;
public:
input();
input(int,int);

Subject : Object Oriented Programming with C++ 82


Swami Sahajanand College of Information Technology BCA SEM -3

void output();
};
void rectangle::input()
{
length=5;
width=10;
}
void rectangle::input(int l, int w)
{
length=l;
width=w;
}
void rectangle::output(void)
{
area=length*width;
cout<<area:
}
void main()
{
rectangle r1, r2; r1.input();
r2.input(10,20);
r1.output();
r2.output();
}
Operator overloading:
The process of making an operator to exhibits different behaviors in different
instances is known as operator overloading.
class rectangle
{
private:
int length;
int width;
public:
void input();
rectangle operator+(rectangle);
void display();
};
Subject : Object Oriented Programming with C++ 83
Swami Sahajanand College of Information Technology BCA SEM -3

void rectangle::input()
{
cout<<"enter length:";
cin>>length;
cout<<"enter width:";
cin>>width;
}
rectangle rectangle::operator+(rectangle r4)
{
rectangle r5; r5.length=length+r4.length;
r5.width=width+r4.width;
return(r5);
}
void rectangle::display()
{
cout<<"length:"<<length;
cout<<"\nwidth:"<<width;
}
void main()
{
clrscr();
rectangle r1,r2,r3;
r1.input();
r2.input();
r3=r1+r2; // r3=r1.operator+(r2);
r3.display();
getch();
}
Virtual Functions:

If there are two functions with the same name in the base class and derived class
and even the address of derived class is assigned to the pointer of base class; it
executes the function of base class. But by declaring the base class function as
virtual, pointer to base class executes the function of derived class. And in this
way base class pointer behaves differently at different situation and applies the
concept of polymorphism. This is also called run time or dynamic polymorphism
because when a function made virtual, C++ determines which function to use at
Subject : Object Oriented Programming with C++ 84
Swami Sahajanand College of Information Technology BCA SEM -3

run time based on the type of object pointed to by the base pointer, rather than
the type of the pointer.

Virtual, as the name implies, is something that exists in effect but not in reality.
The concept of virtual function is the same as a function, but it does not really
exist although it appears in needed places in a program. The object-oriented
programming language C++ implements the concept of virtual function as a
simple member function, like all member functions of the class.

Pure Virtual Function is a Virtual function with no body.


class base
{
public:
virtual void display();
virtual void show();
};
void base::display()
{
cout<<"\nbase class display() function";
}
void base::show()
{
cout<<"\nbase class show() function";
}
class derived: public base
{
public:
void display();
void show();
};
void derived::display()
{
cout<<"\nderived class display() function";
}
void derived::show()

Subject : Object Oriented Programming with C++ 85


Swami Sahajanand College of Information Technology BCA SEM -3

{
cout<<"\nderived class show() function";
}
void main()
{
clrscr();
base *b;
derived d; b=&d;
b->display();
b->show();
getch();
}
Runtime Polymorphism-1
#include<iostream.h> #include<conio.h> #include<string.h>
class media
{
protected:
char title[20];
float price;
public:
media(char *ptr,float p)
{
strcpy(title,ptr);
price = p;
} 5
virtual ~ media()
{
cout<<"\nvirtual destructor called..."<<endl;
}
virtual void display() = 0;
// virtual void display() = {}
};
class CD : public media
{
Subject : Object Oriented Programming with C++ 86
Swami Sahajanand College of Information Technology BCA SEM -3

private:
char c_type[15];
int qty;
public:
CD(char *ptr,float p,char *c,int q) : media(ptr,p)
{
strcpy(c_type,c); qty = q;
}
void display();
};
void CD::display()
{
cout<<"\nTitle : "<<title;
cout<<"\nCD Type : "<<c_type;
cout<<"\nPrice : "<<price;
cout<<"\nQuality : "<<qty;
cout<<"\nAmount : Rs. "<<qty*price;
}
class Floppy : public media
{
private:
char f_type[15];
int qty;
public:
Floppy(char *ptr,float p,char *c,int q) : media(ptr,p)
{
strcpy(f_type,c); qty = q;
}
void display();
};
void Floppy::display()
{
cout<<"\nTitle : "<<title;
cout<<"\nFloppy Type : "<<f_type;

Subject : Object Oriented Programming with C++ 87


Swami Sahajanand College of Information Technology BCA SEM -3

cout<<"\nPrice : "<<price;
cout<<"\nQuality : "<<qty;
cout<<"\nAmount : Rs. "<<qty*price;
}
void main()
{
clrscr();
CD cd1("Samsung",10.00,"700MB/80 MIN",5);
Floppy fl1("Sony",12.00,"1.44MB",5);
media *list[2];
list[0] = &cd1;
list[1] = &fl1;
cout<<"\t\t\t...Media Detail..."<<endl;
cout<<"...CD Detail..."<<endl;
list[0]->display();
cout<<"\n\n\n...Floppy Detail..."<<endl;
list[1]->display();
getch();
}
Runtime Polymorphism-2

#include<iostream.h>
#include<conio.h>
#include<string.h>
class media
{
protected:
char title[50];
float price;
public:
media(char *s, float a)
{
strcpy(title,s); price = a;
}
Subject : Object Oriented Programming with C++ 88
Swami Sahajanand College of Information Technology BCA SEM -3

virtual void display(){ }


};
class book : public media
{
int pages; public:
book(char *s, float a, int p):media(s,a)
{
pages = p;
}
void display();
};
class tape : public media
{
float time;
public:
tape(char *s, float a,float t):media(s,a)
{
time = t;
}
void display();
};
void book :: display()
{
cout<<"\n Title : "<<title;
cout<<"\n Pages : "<<pages;
cout<<"\n Price : "<<price;
}
void tape :: display()
{
cout<<"\n Title : "<<title;
cout<<"\n play time : "<<time << "mins";
cout<<"\n Price: "<<price;
}
void main()
{

Subject : Object Oriented Programming with C++ 89


Swami Sahajanand College of Information Technology BCA SEM -3

char *title = new char[30];


float price ,time;
int pages;
clrscr();

cout<<"\n Enter book details : ";


cout<<"Title : ";cin>>title;
cout<<"Price : ";cin>>price;
cout<<"pages : ";cin>>pages;

book book1(title, price, pages);

cout<<"\n Enter tape details :";


cout<<"Title ";
cin>>title;
cout<<"Price ";
cin>>price;
cout<<"Play time(mins):";
cin>>time;
tape tape1(title, price, time);
media* list[2];
list[0] = &book1;
list[1] = &tape1;
cout<<"\n Media details";
cout<<"\n......Book ";
list[0]->display();

cout<<"\n.....Tape ";
list[1]->display();
getch();
}
Pure Virtual Function
/* runtime polymorphism */
#include<conio.h>
#include<iostream.h>
#include<string.h>
class detail

Subject : Object Oriented Programming with C++ 90


Swami Sahajanand College of Information Technology BCA SEM -3

{
protected:
char *name;
int age;
int empno;
public:
void showdetail()
{
cout<<endl<<"Name is "<<name;
cout<<endl<<"age is "<<age;
cout<<endl<<" empno is"<<empno;
}
detail(char *p, int a, int e)
{
strcpy(name,p);age=a; empno=e;
}
virtual void display()=0; /* pure virtual function*/
/* do nothing bacause it has no defination */
};
class clerk : public detail
{
private:
int basic;
int bonus;
int total;
public:
clerk(char *p, int a, int e,int ba, int bo) : detail(p,a,e)
{
cout<<endl<<"...........constructor is called ";
basic=ba;
bonus=bo;
total=basic+bonus;
}
void display()
{

Subject : Object Oriented Programming with C++ 91


Swami Sahajanand College of Information Technology BCA SEM -3

cout<<endl<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
cout<<endl<<" basic is :- "<<basic;
cout<<endl<<" bouns is :- "<<bonus; cout<<endl<<" total is :- "<<total;
}
};

class manager : public detail


{
private:
int basic;
int tada;
int total;
public:
manager(char *p, int a, int e,int ba, int bo) : detail(p,a,e)
{
cout<<endl<<"...............constructor is called ";
basic=ba; tada=bo;
total=basic+tada+5000;
}
void display()
{
cout<<endl<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
cout<<endl<<" basic is :- "<<basic;
cout<<endl<<" ta+da is :- "<<tada; cout<<endl<<" total is :- "<<total;
}
};
void main()
{
char *ename;
int a,b,c,d;
clrscr();
cout<<endl<<" Please provide detail for clerk";
cout<<endl<<" Enter name ";
cin>>ename;

Subject : Object Oriented Programming with C++ 92


Swami Sahajanand College of Information Technology BCA SEM -3

cout<<"Enter age ";


cin>>a;
cout<<"Enter employee number ";
cin>>b;
cout<<" Enter basic salary ";
cin>>c;
cout<<" Enter bouns ";
cin>>d;
clerk c1(ename,a,b,c,d);
cout<<endl<<" Please provide detail for manager ";
cout<<endl<<" Enter name ";
cin>>ename;
cout<<"Enter age ";
cin>>a;
cout<<"Enter employee number ";
cin>>b;
cout<<" Enter basic salary ";
cin>>c;
cout<<" Enter TA+DA ";
cin>>d;
manager m1(ename,a,b,c,d);
/* using pointer to access member function */
detail *point[2];
point[0]=&c1;
point[1]=&m1;
point[0]->display();
point[1]->display();
getch();
}
This Pointer:
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking
object.
Subject : Object Oriented Programming with C++ 93
Swami Sahajanand College of Information Technology BCA SEM -3

Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.
#include<iostream.h>
#include<conio.h>
#include<string.h>

class person
{
char name[20]; float age;
public:
person()
{
name[0] = NULL; age = 0;
}
person(char s[],float a)
{
strcpy(name,s); age = a;
}
person greater(person x)
{
if(x.age >= age)
return x;
else
}
return *this;
void display()
{
cout<<"Name : "<<name<<endl;
cout<<"Age :"<<age<<endl;
}
};
void main()
{
clrscr();
person p1("Ajay",37.5);
person p2("Vijay",29.0);

Subject : Object Oriented Programming with C++ 94


Swami Sahajanand College of Information Technology BCA SEM -3

person p3("Sanjay",22.5);

person p;
p = p1.greater(p3);
cout<<"Elder is : "<<endl; p.display();
getch();
}
Pointers to derived classes
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
class Base
{
public:
void display()
{
cout<<"\n Display Base";
}
virtual void show()
{
cout<<"\n Show base";
}
};
class Derived : public Base
{
public:
void display()
{
cout<<"\n Display Derived";
}
void show()
{
cout<<"\n Show Derived";
}
};
void main()
{
clrscr();
Subject : Object Oriented Programming with C++ 95
Swami Sahajanand College of Information Technology BCA SEM -3

Base B;
Derived D;
Base *bptr; // base pointer cout<<"\n bptr points to Base \n";
bptr= &B; // base address
bptr->display(); //calls base
bptr->show(); //calls base

cout<<"\n\n bptr points to Derived \n";


bptr=&D;
bptr->display(); //calls Derived
bptr->show(); //calls Derived
getch();
}
#include<iostream.h>
#include<conio.h>
/* When an object belonging to the subclass is constructed ,superclass constructor
is called prior to the subclass constructor.
Destructor goes in a reverse way; Derived class destructor is executed before a
base class*/

class poly
{
protected:
int width,height;
public:
void setval(int a,int b)
{
width = a; height = b;
}
virtual float area() = 0;
void printarea()
{
cout<<this->area()<<endl;
}
virtual ~poly()
{
cout<<"Poly Destructor Called..."<<endl;

Subject : Object Oriented Programming with C++ 96


Swami Sahajanand College of Information Technology BCA SEM -3

}
};
class rect : public poly
{
public:
float area()
{
cout<<"Class Rect Called..."<<endl;
cout<<"Rect Area Calculated"<<endl;
return (width * height);
}
~rect()
{
cout<<"Rect Destructor Called..."<<endl;
}
};
class tringle : public poly
{
public:
float area()
{
cout<<"\nClass Tringle Called..."<<endl;
cout<<"Tringle Area Calculated"<<endl;
return (width * height)/2.0;
}
~tringle()
{
cout<<"\nTringle Destructor Called..."<<endl;
}
};
void main()
{
clrscr();
rect r;
tringle t;
poly *list[2];
list[0] = &r;

Subject : Object Oriented Programming with C++ 97


Swami Sahajanand College of Information Technology BCA SEM -3

list[1] = &t;
list[0]->setval(4,5);
list[0]->printarea();
list[1]->setval(5,5);
list[1]->printarea();
getch();
}
Virtual Constructors and Destructors:
The virtual mechanism works only when we have a base class pointer to a derived
class object.
In C++, the constructor cannot be virtual, because when a constructor of a class is
executed there is no virtual table in the memory, means no virtual pointer defined
yet. So, the constructor should always be non-virtual.
But virtual destructor is possible.
#include<iostream>
using namespace std;
class b
{
public: b()
{
cout<<"Constructing base \n";
}
virtual ~b()
{
cout<<"Destructing base \n";
}
};
class d: public b
{
public: d()
{
}
~d()
{
}
};
int main()

Subject : Object Oriented Programming with C++ 98


Swami Sahajanand College of Information Technology BCA SEM -3

{
d *derived = new d();
b *bptr = derived;
delete bptr;
return 0;
}

Output

Constructing base
Constructing derived
Destructing derived
Destructing base

Subject : Object Oriented Programming with C++ 99


Swami Sahajanand College of Information Technology BCA SEM -3

Subject : Object Oriented Programming with C++ 100


Swami Sahajanand College of Information Technology BCA SEM -3

Answer:
Q-1(A)
Function:
A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can
define additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is such that
each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program
can call. For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and many more
functions.
A function is known with various names like a method or a sub-routine or a
procedure etc.
Member Function:
• Member functions can be defined in two places:
1 Outside the class definition.
2 Inside the class definition.
Outside the class definition:-
• Member functions that are declared inside a class have to be defined
separately outside the class.
• Their definitions are very much like the normal functions.
• They should have a function header and a function body.

Subject : Object Oriented Programming with C++ 101


Swami Sahajanand College of Information Technology BCA SEM -3

• An important difference between a member function and a normal function is


that a member function incorporates a membership ‘identity label’ in the
header.
• Syntax :-
return-type class-name : : function-name(argument declaration)
{
function body
}
Example :-
void item :: getdata(int a)
{
number = a;
}
Inside the class definition:-
• Another method of defining a member function is to replace the function
declaration by the actual function defining inside the class.
Example :-
class item
{
private:
int number;
float cost;
public:
void putdata(void) // definition inside the calss
{
cout<<number<<endl;
}
};
Inline Function

• “An inline function is a function that is expanded in line when it is invoked.”


• To eliminate the cost of calls to small functions, C++ proposes a new feature
called inline function.

Syntax :-
inline function-header
Subject : Object Oriented Programming with C++ 102
Swami Sahajanand College of Information Technology BCA SEM -3

{
function body
}
Example:-
Inline int mul(int x,int y)
{
return (x*y); // 20
}
int main( )
{
cout<<mul(5,4);
getch();
return 0;
}
O/P→20
Friend Function
• When we want to access private data of an particular class at that time we
declare function as a friend.
• The functions that are declared with the keyword friend are known as “friend
functions”.
• The function declaration should be preceded by the keyword friend.
• It is not a member of any class.
• A function can be declared as a friend in any number of classes.
Program :-
// Friend function in two classes
#include<iostream.h>
#include<conio.h>
class abc; // forward declaration class xyz
{
int x; public:
void setvalue(int i)
{
x=I;
}
friend void max(xyz,abc);
};
Subject : Object Oriented Programming with C++ 103
Swami Sahajanand College of Information Technology BCA SEM -3

class abc
{
int a;
public:
void setvalue(int i)
{
a=I;
}
friend void max(xyz,abc);
};
void max(xyz m, abc n)
{
if(m.x>=n.a)
cout<<m.x;
else
cout<<n.a;

}
int main()
{
abc a1;
a1.setvalue(10);
xyz x1;
x1.setvalue(20);
max(a1,x1);
getch();
return 0;
}
O/P → 2
Characteristics of friend function
• It is not in the scope of the class to which it has been declared as friend.
• Since it is not in the scope of the class, it cannot be called using the object of
that class.
• It can be invoked like a normal function without the help of any object.

Subject : Object Oriented Programming with C++ 104


Swami Sahajanand College of Information Technology BCA SEM -3

• Unlike member functions, it cannot access the member names directly and
has to use an object name and dot membership operator with each member
name. (e.g. A.x)
• It can be declared either in the public or the private part of a class without
affecting its meaning.
• Usually, it has the objects as arguments.

Q- 1(A)(I)
There may be a situation, when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general from of a loop statement in most of the
programming languages −
C++ programming language provides the following type of loops to handle looping
requirements.

Sr.No Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition


is true. It tests the condition before executing the loop body.

2 for loop

Execute a sequence of statements multiple times and abbreviates


the code that manages the loop variable.

3 do...while loop

Like a ‘while’ statement, except that it tests the condition at the end

Subject : Object Oriented Programming with C++ 105


Swami Sahajanand College of Information Technology BCA SEM -3

of the loop body.

4 nested loops

You can use one or more loop inside any another ‘while’, ‘for’ or
‘do..while’ loop.

Q – 1(A)(II)
C C++
Language Language
It is developed by Denis Ritchie. It is developed by Bjarne Stroustrup.
It is Only C (without classes). It is C with Classes.
It is Procedure Oriented It is Object Oriented Programming
Programming (POP) language. (OOP) language.
It follows Top-down approach. It follows Bottom-up approach.
Data move freely around the Data is hidden and cannot be
system from function to function. accessed by external functions.
A program is divided into function. A program is divided into objects.
Security not maintains to hide data in Security is maintaining to hide data in
C. C++.
Software complexity cannot be Software complexity can be easily
easily managed. managed using reusability of code.
In C, we declare variable at the In C++, we can declare variable
top of program. anywhere in the program.

Q – 2(A)
Operator Overloading:
You can redefine or overload most of the built-in operators available in C++. Thus, a
programmer can use operators with user-defined types as well.

Subject : Object Oriented Programming with C++ 106


Swami Sahajanand College of Information Technology BCA SEM -3

Overloaded operators are functions with special names: the keyword "operator"
followed by the symbol for the operator being defined. Like any other function, an
overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns
final Box object. Most overloaded operators may be defined as ordinary non-
member functions or as class member functions. In case we define above function
as non-member function of a class then we would have to pass two arguments for
each operand as follows −
Box operator+(const Box&, const Box&);

The unary operators operate on a single operand and following are the examples of
Unary operators −
• The increment (++) and decrement (--) operators.
• The unary minus (-) operator.
• The logical not (!) operator.
The unary operators operate on the object for which they were called and normally,
this operator appears on the left side of the object, as in !obj, -obj, and ++obj but
sometime they can be used as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as
well as postfix usage.
#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)
Subject : Object Oriented Programming with C++ 107
Swami Sahajanand College of Information Technology BCA SEM -3

{
feet = f;
inches = i;
}

// method to display distance


void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);

D1; // apply negation


D1.displayDistance(); // display D1

D2; // apply negation


D2.displayDistance(); // display D2
return 0;
}
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11

Subject : Object Oriented Programming with C++ 108


Swami Sahajanand College of Information Technology BCA SEM -3

The binary operators take two arguments and following are the examples of Binary
operators. You use binary operators very frequently like addition (+) operator,
subtraction (-) operator and division (/) operator.
Following example explains how addition (+) operator can be overloaded. Similar
way, you can overload subtraction (-) and division (/) operators.
#include <iostream>
using namespace std;

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;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
// Main function for the program
Subject : Object Oriented Programming with C++ 109
Swami Sahajanand College of Information Technology BCA SEM -3

int main()
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// 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;

// Add two object as follows:


Box3 = Box1 + Box2;

// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << 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
Volume of Box3 : 5400

Subject : Object Oriented Programming with C++ 110


Swami Sahajanand College of Information Technology BCA SEM -3

OR

Q- 2(A)(I)

Constructor and its types:


Main goal of creating class to make user defined data type, which is similar to build-
in-data-type. We know that we can initialize the built-in-data-type variable during
declaration. But we cannot initialize the class object during declaration in this way.
int a = 20; // Simple built-in-data-type variable.
Allow student s=30; // Not allow. Student is class object To initialize our class object
during creating (declaration) we are using special member function known as
constructor. The name of this member function is same as your class name. This
function is called when we create object. It is known as constructor because it
constructs the value of the variable inside the class.
Default Constructors
Default constructors do not take any parameters. If a default constructor is not
provided by the programmer explicitly, then the compiler provides a implicit default
constructor. In that case, the default values of the variables are 0.
PARAMETERIZED CONSTRUCTOR: -
In default constructor we can initialize all object variable by fixed value. But
sometimes it is necessary to initialize the all object variable with different value. For
that we have to use parameterized constructor.
“A constructor function which receives argument is called parameterized
constructor.”
e.g. Consider the following class ‘Rectangle’ in which we are initializing member of
class ‘length’ and ‘width’ with different value for each object.
class Rectangle
{
int length;
int width;
public :
Rectangle(int, int); // Declaration of constructor function
}
Rectangle :: Rectangle(int l, int w)
{ // Definition of constructor function
length = l;
Subject : Object Oriented Programming with C++ 111
Swami Sahajanand College of Information Technology BCA SEM -3

width = w;
}
We can pass argument to the constructor function during creating object by two
ways:
By calling the constructor explicitly:
e.g. Rectangle r1 = Rectangle(20, 30);
Here we are passing 20 and 30 which received as ‘l’ and ‘w’ in constructor.
By calling constructor implicitly: This method is also known as shortcut method. It is
easy to write and read.
e.g. Rectangle r2(20, 30);

So the main function for the above class is:


void main( )
{
Rectangle r1=Rectangle(20,30); // Explicit call
Rectangle r2(20,30); // Implicit call
………
}
When we are passing argument (parameter) to the constructor function it is known
as the parameterized constructor.

COPY CONSTRUCTOR: -
We can pass any variable (either primary data type, array, structure or class object)
as argument in function but we cannot pass the same class object as argument. But
we can pass the reference of the same class object as argument. This is known as
copy constructor.
“In constructor when reference to the same class object is passed as argument then
it is called as copy constructor.” e.g. Consider the following class ‘Rectangle’ in which
we are initializing member of class ‘length’ and ‘width’ by passing reference of class
‘Rectangle’.
class Rectangle
{
Subject : Object Oriented Programming with C++ 112
Swami Sahajanand College of Information Technology BCA SEM -3

int length;
int width;
public :
Rectangle(Rectangle &); // Declaration of constructor function
}
Rectangle :: Rectangle(Rectangle &o)
{ // Definition of constructor function
length =o.length;
width = o.width;
}

We can initialize the copy constructor by three ways:


By calling the constructor explicitly:
e.g. Rectangle r2 = Rectangle(r1);

By calling constructor implicitly:


This method is also known as shortcut method. It is easy to write and read.
e.g. Rectangle r2(r1);

Copy Initialization: “The way of initialization of object using copy constructor in


form of
classname object1 = object2
is known as copy initialization”
e.g. Rectangle r2 = r1; // Copy initialization

Q-2(A))(II)

Destructor with example:


Destructors in C++ are members functions in a class that delete an object. They are called
when the class object goes out of scope such as when the function ends, the program
ends, a delete variable is called etc.

Subject : Object Oriented Programming with C++ 113


Swami Sahajanand College of Information Technology BCA SEM -3

Destructors are different from normal member functions as they don’t take any argument
and don’t return anything. Also, destructors have the same name as their class and their
name is preceded by a tilde(~).
A program that demonstrates destructors in C++ is given as follows.
Example
#include<iostream>
using namespace std;
class Demo
{
private:
int num1, num2;
public:
Demo(int n1, int n2)
{
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2;
}
void display()
{
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo()
{
cout<<"Inside Destructor";
}
};
int main()
{
Demo obj1(10, 20);
obj1.display();
return 0;
Subject : Object Oriented Programming with C++ 114
Swami Sahajanand College of Information Technology BCA SEM -3

}
Output
Inside Constructor
num1 = 10
num2 = 20
Inside Destructor
Q-3(A)

Inheritance and its all types with example:


Reusability is an important feature of Object oriented programming language.
It is good if we are using existing thing rather than creating the new thing. It
can save time, money and increate reliability. For example, class that already
created, tested can be reused again to save same effort.

C++ supports the concept of reusability using inheritance (derivation).

Inheritance is a technique to create a new class from existing class. In


inheritance the old class is known as base class or parent class or super class
and the new class is known as derived class or sub class or child class.

Example of Single inheritance :

class student
{
private:
int enroll;
char name[20];
char course[20];
public:
void input_stud();
void display_stud();
Subject : Object Oriented Programming with C++ 115
Swami Sahajanand College of Information Technology BCA SEM -3

};

void student::input_stud()
{
cout<<"enter enroll:";
cin>>enroll;
cout<<"enter name:";
cin>>name;
cout<<"enter course:";
cin>>course;
}
void student::display_stud()
{
cout<<"enroll is:"<<enroll;
cout<<"\nname is:"<<name;
cout<<"\ncourse is:"<<course;
}
class exam:public student
{
private:
int msub1;
int msub2;
int msub3;
public:
void input_exam();
void display_exam();
};
void exam::input_exam()
{
cout<<"enter marks of subject1:";
cin>>msub1;
cout<<"enter marks of subject2:";
cin>>msub2;
cout<<"enter marks of subject3:";
cin>>msub3;
}
void exam::display_exam()
{
cout<<"\nmarks in subject1 is:"<<msub1;
Subject : Object Oriented Programming with C++ 116
Swami Sahajanand College of Information Technology BCA SEM -3

cout<<"\nmarks in subject2 is:"<<msub2;


cout<<"\nmarks in subject3 is:"<<msub3;
}
void main()
{
clrscr();
exam e1;
e1.input_stud();
e1.input_exam();
e1.display_stud();
e1.display_exam();
getch();
}

Multiple inheritance:
If a derived class is created from more than one base class then it is
known as multiple inheritance.

Example:
#include<iostream.h>
#include<conio.h>
class student
{
protected:
char course[20];
char name[20];
int enroll;

Subject : Object Oriented Programming with C++ 117


Swami Sahajanand College of Information Technology BCA SEM -3

};
class exam
{
protected:
char etype[20];
int msub1;
int msub2;
int msub3;
};
class result:public student, public exam
{
private:
int tmarks;
public:
void input();
void total();
void display();
};
void result::input()
{
cout<<"enter enroll:";
cin>>enroll;
cout<<"enter name:";
cin>>name;
cout<<"enter course:";
cin>>course;
cout<<"enter exam type:";
cin>>etype;
cout<<"enter marks of subject1:";
cin>>msub1;
cout<<"enter marks of subject2:";
cin>>msub2;
cout<<"enter marks of subject3:";
cin>>msub3;
}

Subject : Object Oriented Programming with C++ 118


Swami Sahajanand College of Information Technology BCA SEM -3

void result::total()
{
tmarks=msub1+msub2+msub3;
}
void result::display()
{
cout<<"enroll:"<<enroll;
cout<<"\nname:"<<name;
cout<<"\ncourse:"<<course;
cout<<"\nexam type:"<<etype;
cout<<"\n total marks:"<<tmarks;
}

void main()
{
clrscr();
result r1;
r1.input();
r1.total();
r1.display();
getch();
}
Hierarchical Inheritance:

The mechanism of deriving two or more classes from the same class is known as
Hierarchical inheritance. The base class will include all the features that are
common to the subclasses. A subclass can serve as a base class for the lower level
classes and so on.

Subject : Object Oriented Programming with C++ 119


Swami Sahajanand College of Information Technology BCA SEM -3

class student
{
protected:
char course[20];
char name[20];
int enroll;
};
class fee:public student
{
private:
int adminfee;
int hostelfee;
int transpfee;
int totalfee;
public:
void input();
void total();
void display();
};
void fee::input()
{
cout<<"enter admission fee:";
cin>>adminfee;
cout<<"enter hostel fee:";
cin>>hostelfee;
Subject : Object Oriented Programming with C++ 120
Swami Sahajanand College of Information Technology BCA SEM -3

cout<<"enter transport fee:";


cin>>transpfee;
}
void fee::total()
{
totalfee=adminfee+hostelfee+transpfee;
}
void fee::display()
{
cout<<"total fee:"<<totalfee;
}
class exam:public student
{
private:
char etype[20];
int msub1;
int msub2;
int msub3;

public:
void input();
void display();
};
void exam::input()
{
cout<<"enter exam type:";
cin>>etype;
cout<<"enter marks of subject1:";
cin>>msub1;
cout<<"enter marks of subject2:";
cin>>msub2;
cout<<"enter marks of subject3:";
cin>>msub3;
}
Subject : Object Oriented Programming with C++ 121
Swami Sahajanand College of Information Technology BCA SEM -3

void exam::display()
{
cout<<"\nexam type:"<<enroll;
cout<<"\nsubject1:"<<msub1;
cout<<"\nsubject2:"<<msub2;
cout<<"\nsubject3:"<<msub3;
}
void main()
{ clrscr();
exam e1;
fee f1;
f1.input();
f1.total();
f1.display();
e1.input();
e1.display();
getch();
}

Multilevel inheritance:
When one derived class is created from base class and from that derived class if
we are creating new derived class then this kind of chain is known as multilevel
inheritance.

Subject : Object Oriented Programming with C++ 122


Swami Sahajanand College of Information Technology BCA SEM -3

Multilevel inheritance:

The mechanism of deriving a class from another ‘derived class’ is known as


multilevel inheritance.
class student
{
protected:
char course[20];
char name[20];
int enroll;
};
class exam:public student
{
protected:
char etype[20];
int msub1;
int msub2;
int msub3;
};

class result:public exam


{
private:
Subject : Object Oriented Programming with C++ 123
Swami Sahajanand College of Information Technology BCA SEM -3

int tmarks;
public:
void input();
void total();
void display();
};
void result::input()
{
cout<<"enter enroll:";
cin>>enroll;

cout<<"enter name:";
cin>>name;
cout<<"enter course:";
cin>>course;
cout<<"enter exam type:";
cin>>etype;
cout<<"enter marks of subject1:";
cin>>msub1;
cout<<"enter marks of subject2:";
cin>>msub2;
cout<<"enter marks of subject3:";
cin>>msub3;
}
void result::total()
{
tmarks=msub1+msub2+msub3;
}
void result::display()
{
cout<<"enroll:"<<enroll;
cout<<"\nname:"<<name;
cout<<"\ncourse:"<<course;
cout<<"\nexam type:"<<etype;

Subject : Object Oriented Programming with C++ 124


Swami Sahajanand College of Information Technology BCA SEM -3

cout<<"\n total marks:"<<tmarks;


}
void main()
{
clrscr();
result r1;
r1.input();
r1.total();
r1.display();
getch();
}
Hybrid inheritance:
When more than one types of inheritance discussed above (Single, Multiple,
Hierarchical, or Multilevel) is combined then this combination is known as
hybrid inheritance.
In following figure we have combination of hierarchical and multiple
inheritance.

Hybrid inheritance/ ambiguity in hybrid inheritance/ multipath problem


in inheritance/ virtual base class:

Subject : Object Oriented Programming with C++ 125


Swami Sahajanand College of Information Technology BCA SEM -3

Sometimes we need to apply two or more types of inheritance to design a


program and this type of inheritance is called hybrid inheritance. But in hybrid
inheritance, if multiple paths exit between a base class and derived class through
different intermediate classes, then derived class inherits the members of the
base class more than one time and it results in ambiguity. Here, base class is
called indirect base class and intermediate base classes are called direct base
classes.

To avoid this ambiguity, the indirect base class is made virtual base class and to
define base class as virtual, a keyword virtual is appended when extending the
direct base classes from the indirect base class as given in the example. In this
way, when we define the indirect base class virtual, compiler take care that only
one copy of that class is inherited, regardless of how many inherited paths exist
between the virtual base class and the derived class.

/* example of Hybrid inheritance */

#include<iostream.h>
#include<conio.h>
class student
{
protected:
char *name;
int roll_no;
public:
student(char *ptr,int r)
{
name=ptr;
roll_no=r;
}
};

class test:public student


{
public:

Subject : Object Oriented Programming with C++ 126


Swami Sahajanand College of Information Technology BCA SEM -3

int sub1;
int sub2;
test(char *ptr,int r,int s1,int s2):student(ptr,r)
{
sub1=s1;
sub2=s2;
}
};
class sports
{
protected:
int internal;
public:
void getdata()
{
cout<<endl<<"enter internal mark for student:- ";
cin>>internal;
}
void putdata()
{
cout<<endl<<"internal mark is:- "<<internal;
}
};
class result:public test,public sports
{
int total;
float per;
public:
result(char *ptr,int r,int s1,int s2):test(ptr,r,s1,s2)
{
}
void cal()
{
total=sub1+sub2+internal;
Subject : Object Oriented Programming with C++ 127
Swami Sahajanand College of Information Technology BCA SEM -3

per=total/3;
cout<<endl<<"roll_no :- "<<roll_no;
cout<<endl<<"Name:- "<<name;
cout<<endl<<"sub1:- "<<sub1;
cout<<endl<<"sub2:- "<<sub2;
cout<<endl<<"internal mark:- "<<internal;
cout<<endl<<"total:- "<<total;
cout<<endl<<"percentage:- "<<per;
}
};
void main()
{
clrscr();
result st1("mahesh",101,65,75);
st1.getdata();
st1.cal();
getch();
}
Q-3(A)(I)
TYPE CONVERSION: -

In C programming language, when different types of constants and variables


are used in expression then C automatically perform type conversion based on
some fixed rules. Same thing is also allow in C++ programming language.

In assignment operation, variable at the right hand side of assignment


operator is automatically converted to the type of the variable on the left.

int m ;
float x = 3.14654;
m = x;

Here ‘x’ is float variable but it is at the right side of assignment operator so
converted into the integer format. But this will work well when at the both the
side data types are primary data type or both are same type user-defined data
type. But it will create problem when one data type is user-defined data type
Subject : Object Oriented Programming with C++ 128
Swami Sahajanand College of Information Technology BCA SEM -3

and another is primary data type. So for that we have to use some special
function for type conversion.
Following three types of type conversion occurs:

1 Conversion from basic type to the class type.


In this type of conversion the source type is basic type and destination
type is class type.
For example we have class student and one object of student is ‘s’ and
suppose we want to assign the roll number of student ‘s’ by any integer
variable ‘r’ then
s=r
is the example of the conversion form basic to class

2 Conversion from class type to basic type.


In this type of conversion the source type is class type and destination
type is basic type.
For example in above example of basic to class conversion suppose we
want to converts roll no of student class into the some variable ‘r’ then
r=s
is the example of class type to basic type conversion.
3 Conversion from one class to another class type.
In this type of conversion the source type is class type and destination
type is also class type but both class are different.
For example we have created two classes one is item and another is
book. We want to assign the price of item to the price of book. Then we
can do by

B = I // where B is object of class book and I is object of class item.


TYPE CONVERSION FROM BASIC DATA TYPE TO CLASS TYPE: -
The conversion from basic type to class type is performed by two ways:

By using constructor: -
To perform type conversion during creation the object we can use
constructor function. Consider the following case of class ‘Student’ in
which we want to assign the name of student by string variable ‘str’. For
that we are writing one constructor function which accepts one
argument of type string.
class Student
{
Subject : Object Oriented Programming with C++ 129
Swami Sahajanand College of Information Technology BCA SEM -3

int rollno;
char name[30];
public :
// Constructor for type conversion during initialization
Student(char *n)
{
strcpy(name,n);
}
void print()
{
cout << name << endl;
}
};
void main()
{
char str[30]=“abc def";
Student s = str; // Type conversion
s.print();
getch();
}

When we create an object and during creation if we provide the string


value for initialization then it will pass string to the constructor function
and assign to the name of the student.

One thing we have to not during type conversion using the constructor is
that we can pass only one argument. Also we can make type conversion
only at the type of initialization only.

By overloading assignment operator:


We can also make type conversion by using the overloaded assignment
operator. In above example of student class we can add operator function
to overload the assignment operator (=) as under.

class Student
{
……….
Public :
Subject : Object Oriented Programming with C++ 130
Swami Sahajanand College of Information Technology BCA SEM -3

// Overloading assignment operator for type conversion


void operator = (char *n)
{
strcpy(name, n);
}
…..
};
void main( )
{
Student s;
char str[30] = “abc def”;
s = str; // Overloaded assignment operator for type conversion
}
By using overloaded assignment operator we can make the type
conversion at any place in program.
TYPE CONVERSION FROM CLASS TYPE TO BASIC DATA TYPE: -
For conversion from class to basic data type we require special casting
operator function. This is known as the conversion function.
The syntax for the conversion function is as under:
operator typename( )
{
….
….
….
}
For example suppose we want to assign the roll number of student into
one integer variable then we can write the type conversion function as
under in above class
class Student
{
int rollno;
char name[30];

public :
// Conversion function
Operator int( )
{
Subject : Object Oriented Programming with C++ 131
Swami Sahajanand College of Information Technology BCA SEM -3

return (rollno);
}
};
void main( )
{
Student s;
int no;
no = s;
}

Here in above program we have place statement


no = s;
for type conversion. We can also write by following way also. Here we
have specify casting type also.
no = (int) s; // Casting
The conversion function should satisfy the following condition:
• It must be a class member.
• It must not specify the return value even though it returns the
value.
• It must not have any argument.
TYPE CONVERSION FROM ONE CLASS TYPE TO ANOTHER CLASS TYPE: -
Consider the following example:
objX = objY; // Object of different class

In above example we have two objects of two different classes ‘X’ and ‘Y’
and there is conversion from object of class ‘X’ to class ‘Y’. Here object
‘objX’ is called the destination object and ‘objY’ is called the source object.

For this type of conversion from one class to another class we can use
either the constructor function or type conversion function.

Q-3(A)(II)
Nesting of Classes:

Subject : Object Oriented Programming with C++ 132


Swami Sahajanand College of Information Technology BCA SEM -3

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.
A program that demonstrates nested classes in C++ is as follows.

Example
#include<iostream>
using namespace std;
class A
{
public:
class B
{
private:
int num;
public:
void getdata(int n)
{
num = n;
}
void putdata()
{
cout<<"The number is "<<num;
}
};
};
int main()
{
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
Subject : Object Oriented Programming with C++ 133
Swami Sahajanand College of Information Technology BCA SEM -3

}
Output
Nested classes in C++
The number is 9
In the above program, class B is defined inside the class A so it is a nested class. The
class B contains a private variable num and two public functions getdata() and putdata().
The function getdata() takes the data and the function putdata() displays the data. This is
given as follows.
class A
{
public:
class B
{
private:
int num;
public:
void getdata(int n)
{
num = n;
}
void putdata()
{
cout<<"The number is "<<num;
}
};
};
In the function main(), an object of the class A and class B is defined. Then the functions
getdata() and putdata() are called using the variable obj. This is shown below.
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();

Q-4(A)
Polymorphism with example:
Subject : Object Oriented Programming with C++ 134
Swami Sahajanand College of Information Technology BCA SEM -3

The word polymorphism means having many forms. Typically, polymorphism occurs
when there is a hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function
to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two classes

#include <iostream>
using namespace std;

class Shape {
protected:
int width, height;

public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};

class Triangle: public Shape {


public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};

// Main function for the program


int main() {
Shape *shape;
Subject : Object Oriented Programming with C++ 135
Swami Sahajanand College of Information Technology BCA SEM -3

Rectangle rec(10,7);
Triangle tri(10,5);

// store the address of Rectangle


shape = &rec;

// call rectangle area.


shape->area();

// store the address of Triangle


shape = &tri;

// call triangle area.


shape->area();

return 0;
}
When the above code is compiled and executed, it produces the following result −
Parent class area :
Parent class area :
The reason for the incorrect output is that the call of the function area() is being set once
by the compiler as the version defined in the base class. This is called static resolution of
the function call, or static linkage - the function call is fixed before the program is
executed. This is also sometimes called early binding because the area() function is set
during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration of
area() in the Shape class with the keyword virtual so that it looks like this −
class Shape {
protected:
int width, height;

public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
After this slight modification, when the previous example code is compiled and executed, it
produces the following result −
Rectangle class area
Subject : Object Oriented Programming with C++ 136
Swami Sahajanand College of Information Technology BCA SEM -3

Triangle class area


This time, the compiler looks at the contents of the pointer instead of it's type. Hence,
since addresses of objects of tri and rec classes are stored in *shape the respective area()
function is called.
As you can see, each of the child classes has a separate implementation for the function
area(). This is how polymorphism is generally used. You have different classes with a
function of the same name, and even the same parameters, but with different
implementations.
Q-4(A)(I)
Virtual and Pure Virtual Function:

Virtual Function
A virtual function is a function in a base class that is declared using the keyword virtual.
Defining in a base class a virtual function, with another version in a derived class, signals
to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the
program to be based on the kind of object for which it is called. This sort of operation is
referred to as dynamic linkage, or late binding.

Pure Virtual Functions


It is possible that you want to include a virtual function in a base class so that it may be
redefined in a derived class to suit the objects of that class, but that there is no meaningful
definition you could give for the function in the base class.
We can change the virtual function area() in the base class to the following −
class Shape {
protected:
int width, height;

public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}

// pure virtual function


virtual int area() = 0;
};
The = 0 tells the compiler that the function has no body and above virtual function will be
called pure virtual function.
Q-4(A)(II)

Subject : Object Oriented Programming with C++ 137


Swami Sahajanand College of Information Technology BCA SEM -3

Pointer and Virtual Constructor:


This Pointer:
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking
object.
Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.

#include<iostream.h>
#include<conio.h>
#include<string.h>
class person
{
char name[20];
float age;
public:
person()
{
name[0] = NULL;
age = 0;
}
person(char s[],float a)
{
strcpy(name,s);
age = a;
}
person greater(person x)
{
if(x.age >= age)
return x;
else
return *this;
}
void display()
{
cout<<"Name : "<<name<<endl;

Subject : Object Oriented Programming with C++ 138


Swami Sahajanand College of Information Technology BCA SEM -3

cout<<"Age :"<<age<<endl;
}
};
void main()
{
clrscr();
person p1("Ajay",37.5);
person p2("Vijay",29.0);
person p3("Sanjay",22.5);

person p;
p = p1.greater(p3);

cout<<"Elder is : "<<endl;
p.display();
getch();
}
Virtual Constructors and Destructors:
The virtual mechanism works only when we have a base class pointer to a derived
class object.
In C++, the constructor cannot be virtual, because when a constructor of a class is
executed there is no virtual table in the memory, means no virtual pointer defined
yet. So, the constructor should always be non-virtual.
But virtual destructor is possible.
#include<iostream>
using namespace std;
class b
{
public:
b()
{
cout<<"Constructing base \n";
}

virtual ~b()
{
cout<<"Destructing base \n";
Subject : Object Oriented Programming with C++ 139
Swami Sahajanand College of Information Technology BCA SEM -3

}
};
class d: public b
{
public:
d()
{
cout<<"Constructing derived \n";
}
~d()
{
cout<<"Destructing derived \n";
}
};
int main()
{
d *derived = new d();
b *bptr = derived;
delete bptr;
return 0;
}
Output
Constructing base
Constructing derived
Destructing derived
Destructing base

Subject : Object Oriented Programming with C++ 140

You might also like