BCA Sem 3 C - SSCCM
BCA Sem 3 C - SSCCM
B.C.A. SEM. - 3
UNIT - 1
UNIT - 1
◆ Introduction of OOP
• 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
Applications of C++
• Real-time systems.
• Simulation and modeling.
• Object-oriented databases.
• Hypertext, hypermedia and expert text.
• AI (Artificial Intelligence) and expert systems.
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.
◆ 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.
• 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
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:
• 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’.
Vehicle
Attribute
For Wheeler
Two Wheeler
Patrol Diesel
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.
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
• 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++
• 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
• 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
[data_type] [variable_name];
5. Example Operator
#include <iostream.h>
int main() {
cin>>a;
cin>>b;
int sum;
sum=a+b;
return 0;
C++
}
operator is a symbol that is used to perform mathematical or logical manipulations.
• Arithmetic Operators
• Increment and Decrement Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operator
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Operator Description
++ Increment
−− Decrement
Relational Operators
Operator Description
== Is equal to
!= Is not equal to
> Greater than
< Less
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
Bitwise Operators
Operator Description
| 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
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:
• 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:
• 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:
Union:
union data
{
Char ch[2];
int I;
};
• 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
2) Dynamic array
• int student[ ] example of dynamic array
• Dynamic array are created in the heap using new and released using delete operation.
Pointers:
• 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);
Reference variables:
#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:
• 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 :
• 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
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
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
• 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.
• :: 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;
• We can allocate memory for any data type including user defined variables like union,
structures and classes with the help of new keyword. The general form for one- dimensional
array is :
Syntax :- pointer-variable = new data-type[size];
• 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.
• 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“.
• 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;
}
#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):
• 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:
• 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)
{
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;
}
};
int main( )
{
cout<<mul(5,4); getch();
return 0;
}
O/P→20
Where inline expansion may not work?
• 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 :-
• 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.
• 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:
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.
• 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
• 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.
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.
UNIT - 2
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.
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)
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:
Here we are passing 20 and 30 which received as ‘l’ and ‘w’ in constructor.
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);
}
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:
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:
or
operand op
For binary operation we can call the operator function by:
operand1 op operator2
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)
{
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
// 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()
{
}
Complex(float real, float imag)
{
x = real; y = imag;
}
Complex
operator+(Complex);
void display(void);
};
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 */
};
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 :
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.
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;
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);
};
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);
}
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
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.
We cannot use friend function to overload following operators but we can use only
memberfunction.
Operator Sign Operator Name
= Assignment 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.
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
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();
};
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
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.
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
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.
#include<iostream.h>
#include<conio.h>
class student // Base class
{
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;
}
};
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.
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();
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
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
};
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
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.
UNIT - 4
Polymorphism:
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.
{
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;
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
cout<<"\n.....Tape ";
list[1]->display();
getch();
}
Pure Virtual Function
/* runtime polymorphism */
#include<conio.h>
#include<iostream.h>
#include<string.h>
class detail
{
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()
{
cout<<endl<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
cout<<endl<<" basic is :- "<<basic;
cout<<endl<<" bouns is :- "<<bonus; cout<<endl<<" total is :- "<<total;
}
};
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);
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
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;
}
};
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;
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()
{
d *derived = new d();
b *bptr = derived;
delete bptr;
return 0;
}
Output
Constructing base
Constructing derived
Destructing derived
Destructing base
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.
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.
• 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.
1 while loop
2 for loop
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end
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.
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;
}
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;
// 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
OR
Q- 2(A)(I)
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);
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;
}
Q-2(A))(II)
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)
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
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;
};
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;
}
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.
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
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.
Multilevel inheritance:
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;
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.
#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;
}
};
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: -
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:
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();
}
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.
class Student
{
……….
Public :
Subject : Object Oriented Programming with C++ 130
Swami Sahajanand College of Information Technology BCA SEM -3
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;
}
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:
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);
}
};
Rectangle rec(10,7);
Triangle tri(10,5);
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
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.
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
#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);
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