0% found this document useful (0 votes)
111 views

Data Structures and Object Oriented Programming in C++: Unit-I

This document provides an overview of object-oriented programming concepts in C++, including objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It discusses the basic structure of a C++ program and input/output statements. Key topics covered include class declarations, member functions, preprocessor directives, variables, constants, strings, operators, and manipulators. The document serves as an introduction to object-oriented programming principles and the C++ language.

Uploaded by

Vasantha Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views

Data Structures and Object Oriented Programming in C++: Unit-I

This document provides an overview of object-oriented programming concepts in C++, including objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It discusses the basic structure of a C++ program and input/output statements. Key topics covered include class declarations, member functions, preprocessor directives, variables, constants, strings, operators, and manipulators. The document serves as an introduction to object-oriented programming principles and the C++ language.

Uploaded by

Vasantha Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 40

DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++

Unit-I
PRINCIPLES OF OBJECT ORIENTED PROGRAMMING

 Introduction
 Tokens
 Expressions
 contour Structures
 Functions in C++
 Classes and Objects,
 Constructors and destructors ,
 Operators overloading
 Type conversions.

1.1. Object Oriented Programming Concepts


Object-oriented programming (OOP) is a programming paradigm that uses “Objects “and
their interactions to design applications and computer programs. There are different types of
OOPs are used, they are
1. Object
2. Class
3. Data Abstraction & Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing

1) Object :
Object is the basic unit of object-oriented programming. Objects are identified by its unique
name. An object represents a particular instance of a class. There can be more than one
instance of an object. Each instance of an object can hold its own relevant data. An Object is
a collection of data members and associated member functions also known as methods.

For example whenever a class name is created according to the class an object should be
created without creating object can’t able to use class. The class of Dog defines all possible
dogs by listing the characteristics and behaviors they can have; the object Lassie is one
particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has
brown-and-white fur.

2) Class :
Classes are data types based on which objects are created. Objects with similar properties and
methods are grouped together to form a Class. Thus a Class represents a set of individual
objects. Characteristics of an object are represented in a class as Properties. The actions that
can be performed by objects become functions of the class and is referred to as Methods.

For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR
represents individual Objects. In this context each Car Object will have its own, Model, Year
of Manufacture, Colour, Top Speed, Engine Power etc., which form Properties of the Car
class and the associated actions i.e., object functions like Start, Move, Stop form the Methods
of Car Class.No memory is allocated when a class is created. Memory is allocated only when
an object is created, i.e., when an instance of a class is created.

3) Data abstraction & Encapsulation :


The wrapping up of data and its functions into a single unit is called Encapsulation. When
using Data Encapsulation, data is not accessed directly, it is only accessible through the
functions present inside the class.

Data Abstraction increases the power of programming language by creating user defined data
types. Data Abstraction also represents the needed information in the program without
presenting the details. Abstraction refers to the act of representing essential features without
including the background details or explanation between them.

For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and
many more components. To build the Car class, one does not need to know how the different
components work internally, but only how to interface with them, i.e., send messages to
them, receive messages from them, and perhaps make the different objects composing the
class interact with each other.
4) Inheritance :
Inheritance is the process of forming a new class from an existing class or base class. The
base class is also known as parent class or super class, the new class that is formed is called
derived class.

Derived class is also known as a child class or sub class. Inheritance helps in reducing the
overall code size of the program, which is an important concept in object-oriented
programming.

It is classifieds into different types, they are

 Single level inheritance


 Multi-level inheritance
 Hybrid inheritance
 Hierarchial inheritance

5) Polymorphism :
Polymorphism allows routines to use variables of different types at different times. An
operator or function can be given different meanings or functions. Polymorphism refers to a
single function or multi-functioning operator performing in different ways.

Poly a Greek term ability to take more than one form. Overloading is one type of
Polymorphism. It allows an object to have different meanings, depending on its context.
When an exiting operator or function begins to operate on new data type, or class, it is
understood to be overloaded.

6) Dynamic binding :
It contains a concept of Inheritance and Polymorphism.

7) Message Passing :
It refers to that establishing communication between one place to another.

1.2. Benefits or Advantages of OOPS

 The complexity of software can be managed easily.

 Data hiding concept help the programmer to build secure programs


 Through the class concept we can define the user defined data type.

 The inheritance concept can be used to eliminate redundant code

 The message-passing concept helps the programmer to communicate between


different objects.

 New data and functions can be easily added whenever necessary.

 OOPS ties data elements more closely to the functions that operates on.

1.3. Structure of C++ Program

Include files provides instructions to the compiler to link functions from the system
library.
Eg: #include <iostream.h>
#include – Preprocessor Directive
iostream.h – Header File
 A class is a way to bind and its associated functions together. It is a user
defined datatype. It must be declared at class declaration part.
 Member function definition describes how the class functions are implemented. This
must be the next part of the C++ program.
 Finally main program part, which begins program execution.
main( )
{}
Program execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical and of the program.
1.4. Input / Output statements
Input Stream
Syntax:
cin >> var1 >> var2 >>;
cin – Keyword, it is an object, predefined in C++ to correspond to the standard input
stream.
>> - is the extraction or get from operator
Extraction operation (>>) takes the value from the stream object on its left and places it in
the variable on its right.
Eg:
cin>>x;
cin>>a>>b>>c;
Output Stream:
Syntax:
cout<<var1<<var2;

cout - object of standard output stream


<< - is called the insertion or put to operator

It directs the contents of the variable on its right to the object on its left. Output stream can
be used to display messages on output screen.
Eg:
cout<<a<<b;
cout<<”value of x is”<<x;
cout<<”Value of x is”<<x<<”less than”<<y;
1.5. Tokens
The smallest individual units in a program are known as tokens. C++ has the following
tokens
♦ Keywords
♦ Identifiers
♦ Constants
♦ Strings
♦ Operators
1.5.1. Keywords
• It has a predefined meaning and cannot be changed by the user
• Keywords cannot be used as names for the program variables.
Keywords supported by C++ are:

The specific C++ Keywords


asn new template
catch operator this
class private throw
delete protected try
friend public virtual
inline
1.5.2. Identifiers
Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the
programmer.
Rules for naming these identifiers:
1. Only alphabetic characters, digits and underscores are permitted.
2. The name cannot start with a digit.
3. Uppercase and lowercase letters are distinct.
4. A declared keyword cannot be used as a variable name.
(i) Variables:
It is an entity whose value can be changed during program execution and is known to
the program by a name.
A variable can hold only one value at a time during program execution.
Declaration of Variables
Syntax
datatype variablename;
Datatype
It is the type of data, that is going to be processed within the program
Eg:
int x;
float y,z;
char a;
A variable can be declared anywhere in the program before its first use.
1.5.3. Constants
A quantity that does not change is known as constants.
Types of constants:
• Integer constants - E.g. 123, 25 – without decimal point
• Character constants - E.g. ‘A’, ‘B’, ‘*’, ‘1’
• Real constants - E.g. 12.3, 2.5 - with decimal point
1.5.4. Strings
A sequence of characters is called string. String constants are enclosed in double quotes as
follows
“Hello”
1.5.5. Operators
An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment & decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
9. Manipulators
10. Memory allocate / delete Operators
An expression is a combination of variables, constants and operators written according to the
syntax of the language.
Precedence of Operators

1.6 Manipulators
Manipulators are operators used to format the data display. The commonly used
manipulators are endl, setw.
 endl manipulators
It is used in output statement causes a line feed to be inserted, it has the same effect as using
the newline character “\n” in ‘C’ language.
#include <iostream.h>
main()
{
int a=10, b=20;
cout << “C++ language” << endl;
cout << “A value: “ << a << endl;
cout << “B value:” << b << endl;
}
 setw Manipulator
The setw manipulator is used or specify the field width for printing, the content of the
variable.
Syntax: setw(width);
where width specifies the field width.
int a = 10;
cout << “ A value” << setw(5) << a << endl;

Output:
A value 10
 Symbolic Constant
Symbolic constants are constants to which symbolic names are associated for the purpose of
readability and ease of handling.
• #define preprocessor directive
• const keyword
• enumerated data type
#define preprocessor directive
It associates a constant value to a symbol and is visible throughout the function in which it is
defined.
Syntax:
#define symbol name constant value
Eg
#define max_value 100
#define pi 3.14
The value of symbolic constant will not change throughout the program.
const keyword
Syntax:
const datatype var = constant;
E.g.:
const int max = 100;
main()
{
char x[max];
---------
---------
}
const size = 10;

Allowable statement, default symbolic constant type is integer. Here size is of type int.
Reference Variable:
A reference variable provides an alias (alternative name) for a previously defined
variable.
For example, if we make the variable sum a reference to the variable total, then
sum & total can be used interchangeably to represent that variable.
A reference variable is created as follows:
datatype & ref_name = var_name;
Eg:
float total = 100;
float & sum = total;
cout << sum << total;
Both the variables refer to the same data object in the memory i.e. total, sum 100
1.7. Type Conversion:
(i) Implicit type conversion
(ii) Explicit type conversion
Implicit type conversion
It will be done by the compiler, by following the rule of lower type converted to
higher type.

Eg: int y = 10;


float z = 10.5,x;
x = y+z; (y is converted to float type by compiler)
x = 10.0 + 10.5
x= 20.5 (result var. x is must be float)
Explicit type conversion
It will be performed by the programmer according to the need of this in the program.
Syntax: datatype (var)

Eg: int y = 10;


float z = 2.5;
(resultant type of y+z is float, that is converted explicitly to int type)
x = int (y + z);
Now the result is of int type.
1.8. FUNCTIONS
It is difficult to implement a large program even if it is algorithm is available. To implement
such a program in an easy manner, it should be split into a number of independent tasks,
which can be easily designed, implemented, and managed.

This process of splitting a large program into small manageable tasks and designing them
independently is called Modular Programming. A repeated group of instruction in a program
can be organized as a function. A function is a set of program statements that can be
processed independently.
Advantages
• Reduction in the amount of work and development time.
• Program and function debugging is easier.
• Reduction in size of the program due to code Reusability.

Function Components
• Function declaration or prototype
• Function Definition
• Function call
• Function parameters
• Function return statement
i. Function Prototype or Declaration:
It provides the following information to the compiler
• The name of the function
• The type of the value returned (optional, default is an integer)
• The number and type of the arguments that must be supplied in a call to the function.
• Syntax:
Return type function_name(argu1,argu2,……argun);
Return type - specifies the data type of the value in the return
statement.
Fun_name - name of the function.
Argu1,argu2…argun – type of argument to be passed from calling function to
the called function
• Examples:
int max(int,int);
It informs the compiler that the function max has 2 arguments of the type integer. The
function max() returns an integer values.
void max();
It informs the compiler that the function max has no arguments, max() is not returning
any value.
max();
It informs the compiler that the function max has no arguments.
 The function max() returns an integer values.
 In function prototype default return type is integer.

ii. Function definition:


The function itself is referred to a function definition.
Syntax:
return type function_name(argu1,argu2,……argun) //function declarator
{
function body; }

• The first line of the function definition is known as function declarator, and is
followed by the function body.
• The function delcarator and declaration must use the same function name, the number
of arguments, the arguments type and the return type.
• Function definition is allowed to write in a program either above or below the main ().
• If the function is defined before main (), then function declarator is optional.
• Example:
int max(int x, int y)
{
if(x>y)
return(x);
else
return(y);
}
For this function max() definition, it is declaration must be :
int max(int,int);
iii. Function call:
• A function, which gets life only when a call to the function is made.
• A function call specified by the function name followed by the arguments enclosed in
parenthesis and terminated by a semi colon.
• Syntax:
Function_name(argu1,argu2,……argun) ;
• If a function contains a return type the function call is of the following form:
var= Function_name(argu1,argu2,……argun) ;
• Example:
c=max(a,b);
iv. Function Parameters
• The parameters specified in the function call are known as actual parameters and
those specified in the function declarator (definition) are known as formal parameters
• For example in the main(), the statement c=max(a,b); passes the parameters(actual
parameters) a and b to max().
• The parameters x and y are formal parameters.
• When a function call is made, a one to one correspondence is established between the
actual and the formal parameters.
• The scope of the formal parameters is limited to its function only.
v. Function Return
• Functions can be grouped into two categories:
i. A Function does not have a return value (void function)
ii. Functions that have a return value.
The statements: return(x); and return(y);in function max() are called function return
statements. The caller must be able to receive the value returned by the function.
In the statement c=max(a,b) , The value returned by the function max() returning a value to
the caller.
Limitation of return
A key limitation of the return statement is that it can be used to return only one item from a
function.
Passing Data To Functions
The entity used to convey the message to a function is the function argument. It can be a
numeric constant, a variable, multiple variables, user defined data type, etc.

Passing constants as arguments


The following program illustrates the passing of a numeric constant as an argument to a
function. This constant argument is assigned to the formal parameter which is processed in
the function body.
// Greatest among 2 numbers
#include<iostream.h>
void main()
{
int a,b;
int max(int,int); //function declaration
int c= max(40,35);
cout<<”Greatest is: “<<c;
}
int max(int x,int y)
{
if (x>y)
return(x);
else
return(y);
}
Run:
Enter any 2 integers
40
35
Greatest is: 40
In main(), the statement c=max(40,35); invoke the function max with the constants.
Passing variable as arguments
Similarly to constants, varables can also be passed as arguments to a function.
// Greatest among 2 numbers
#include<iostream.h>
void main()
{
int a,b;
int max(int,int); //function declaration
cout<<”enter two integer ”;
cin>>a>>b;
int c= max(a,b);
cout<<”Greatest is: “<<c;
}
int max(int x,int y)
{
if (x>y)
return(x);
else
return(y);
}
Run:
Enter any 2 integers
40
Greatest is: 40
In main(), the statement c=max(a,b); invoke the function max with the values of a & b
Parameter Passing
• Parameter passing is a mechanism for communication of data and information
between the calling function and the called function.
• It can be achieved by either by passing values or address of the variable.
• C++ supports the following 3 types of parameter passing schemes:
1. Pass by Value
2. Pass by Address
3. Pass by Reference
i. Pass by Value
• The default mechanism of parameter passing is called pass by value.
• Pass by value mechanism does not change the contents of the argument variable in the
calling function, even if they are changed in the called function.
• Because the content of the actual parameter in a calling function is copied to the
formal parameter in the called function.Changes to the parameter within the function
will affect only the copy (formal parameters) and will have no effect on the actual
argument.
ii. Pass by Address:
• C++ provides another means of passing values to a function known as pass by address
mechanism.
• Instead of passing the value, the address of the variable is passed.
• In function, the address of the argument is copied into a memory location instead of
the value.
• Example:
#include<iostream.h>
void swap(int *x,int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
void main()
{
int a,b;
cout<<”enter two integers”;
cin>>a>>b;
swap(&a,&b);
cout<<”value of a and b after calling swap() in main()”;
cout<<a<<setw(5)<<b;
}
Run:
enter two integers
30
50
value of a and b after calling swap() in main()”;
50 30

iii. Pass by Reference


• Passing parameters by reference has the functionality of pass by address and the
syntax of pass by value.
• Any modification made through the formal parameter is also reflected in the actual
parameter.
• To pass as argument by reference, the function call is similar to that of call by value.
• In function declarator, those parameters, parameters, which are to be received by
reference, must be preceded by the address ( & )operator.
• The reference type formal parameters are accessed in the same way as normal value
parameters.
• However, any modification to them will also be reflected in the actual parameter
• Example:
#include<iostream.h>
void swap(int &x,int &y)
{
int t=x;
x=y;
y=t;
}
void main()
{
int a,b;
cout<<”enter two integers”;
cin>>a>>b;
swap(a,b);
cout<<”value of a and b after swap(a,b) in main()”;
cout<<a<<setw(5)<<b;
}
Run:
enter two integers
30
50
value of a and b after swap(a,b) in main()
50 30
1.9. Default Arguments
• Normally a function should specify all the arguments used in the function definition.
• In a c++ function call, when one or more arguments are omitted, the function may be
defined to take default values for the omitted arguments by providing the default
values in the function prototype.
• Hence the feature of default arguments allows the same function to be called with
fewer arguments than defined in the function prototype.
• To establish a default value, the function declaration must be used.
• The compiler checks the function prototype with the arguments in the function call to
provide default values to those arguments, which are omitted.
• Default arguments reduce the burden of passing arguments explicitly at the point of
the function call.
• Example:
#include<iostream.h>
void greatest(int = 50;int=25,int =35);
void main()
{
greatest();
greatest(10);
greatest(75,12);
greatest(15,2,55);
}

1.10. Inline functions


• One of the objectives of using functions in a program is to save memory, which
becomes appreciable when a function is likely to be called many times.
• However, every time a function is called, it takes a lot of extra time in executing a
series of instructions, for task such as jumping to the function, and returning to the
calling function.
• When a function is small, the time required to execute a function is less than the
switch time.
• In C++ a new feature called inline function is used to solve the above problem.
• An inline function is a function that is expanded in line when it is called.
• That is, the compiler replaces the function call with the corresponding function code.
• Inline functions are defined as follows
inline return type fun_name(arguments)
{
function body
}
• Example
inline double cube(double a) {
return(a*a*a);
}
1.11. Function Overloading
• It is possible to define several functions having the same name, but performing
different actions.
• It helps in reducing the need for unusual function name, making the code easier to
read.
• This can be done using the concept Function polymorphism or function overloading.
• Function overloading allows multiple functions to share the same name with different
argument type.
• Function Polymorphism implies that the function definition can have multiple forms.
The definitions must only differ in number of arguments and types of arguments.
• Example: //Multiple swap functions
#include<iostream.h>
void swap(char x, char y)
{
char t=x;
x=y;
y=t;
cout<<”Swapped characters”<<x<<setw(5)<<y;
}
void swap(int x, int y)
{
int t=x;
x=y;
y=t;
cout<<”Swapped integers”<<x<<setw(5)<<y;
}
1.12. Classes
The objects with the same data structure (attribute) and behaviour (operations) are grouped
into a class. All these objects possessing similar properties are grouped into the same unit.
Eg: In the person class all person having similar attributes like Name, Age, Sex and the
similar operations like speak, listen, walk. So, boy and girls objects are grouped into the
person class.
Representation of Class:
Class account {
private: char name[20];
int accounttype;
int accountnumber;
float balance;
public: Deposit( );
Withdraw( );
Enquire( );
};
In this the account class groups the object such as saving account, current account, etc,
Thus, objects having the same structural and behavioral propositions are grouped together to
form a class.
The following points on classes can be noted:
1. A class is a template that unites data and operations.
2. A class is a abstraction of the real world entities with similar properties.
3. A class identifies a set of similar objects.

Classes and Objects:


Class Specification:
The class can be described as a collection of data member along with member
functions. This property of C++, which allows association of data and functions into a
single unit, is called encapsulation. Sometimes classes may not contain any data
members or member function called empty classes.
Syntax for class specification

More than one object can be created with a single statement as,
Class student s1,s2,s3;
Or
Student s1,s2,s3.
Object can also be created by placing these names immediately after the closing brace.
Thus the definition
Class student
{
---------------
---------------
} s1,s2,s3;

Accessing class members:


Once an object of a class has been created, there must be a provision to access its members.
This is achieved by using the member access operator, dot(.).
Syntax: for accessing datamember of a class

Syntax for accessing member function of a class

Defining Member Function


The data members of a class must be declared within the body of the class, whereas the
member functions of the class can be defined in any one of the following ways.
• Inside the class specification
• Outside the class specification
The syntax of a member function definition changes depending on whether it is defined
inside or outside the class specification, but it performs the same operation.
(a) Member function inside the class body:
(b) Member functions outside the class body
Data Hiding:
Data is hidden inside a class, so the unauthorized access is not possible, which is the key
feature of OOP.
All the data and functions defined in a class are private by default.
Methods of Data hiding
• Private
• Public
• Protected
Access Specifiers
Private members:
In this only the member functions of the same class can access these members.
The private members of a class are inaccessible outside the class.
class person
{
private:
int age; //private data
int getage( ): //private function
... .
}
person p1;
a = p1.age; //cannot access private data //error
p1.getage( ); //Error access

i.e., we can access the private members by using objects.


Protected member
The access control of the protected members is similar to that of private members.
The access control of protected members is shown below:
Class person
{

protected:
... .
int age; // protected data
int getage( ): //protected function
... .
};
person p1; // Cannot access protected members
a = p1.age;
p1.getage( );

Public Members
All data members and function declared in the public section of the class can be accessed
without any restriction from anywhere in the program.
Eg:
class person
{
public:
int age; //public data
int getage( ); //public function
}
person p1;
a = p1.age; // can access public data
p1.getage( ); // can access public function

Passing Objects Arguments


• It is possible to have functions which accept objects of a class as arguments, just as
there are functions which accept other variables as arguments.
• An object can be passed as an argument to a function by the following ways:
1. Passing object by value, a copy of the entire object is passed to the
function
2. Passing object by reference, only the address of the object is passed
implicitly to the function.
3. Passing object by pointer, the address of the object is passed explicitly to the
function
Passing Object by value
In this case a copy of the object is passed to the function and any modifications made
to the object inside the function are not reflected in the object used to call the function.
Example:
#include<iostream.h>
class test
{
int m1,m2;
public:
void get() {
cin>>m1>>m2;
}
void read(test t3) {
m1=t3.m1;
m2=t3.m2;
}
void display() {
cout<<m1<<m2;
}
};
void main() {
test t1;
cout<<”Enter Ist object data”;
t1.get();
cout<<”display Ist object data”;
t1.display();
test t2;
cout<<”copy of object1 to object2”;
t2. read(t1);
cout<<”display 2nd object data”;
t2.display();
}
Run:
Enter Ist object data
34
56
display Ist object data
34
56
copy of object1 to object2
display 2nd object data
34
56
The members of t1 are copied to t2. Any modification made to the data members of
the objects t1 and t2 are not visible to the caller’s actual parameter
1.13. CONSTRUCTOR
Constructor is a special member function. This is used to give initial values to member
variables.

The general form is:


constructor_name(parameters) {
statements to give initial values to member variables }
Rules:

 It should be declared as public.


 No return type needed.
 When the object is declared for the class, it automatically executes the constructor and
initialized the variables.

There are two types of constructors. They are:


1. Constructor without parameters
2. Constructor with parameters (or) parameterized constructor

Constructor without parameters


If a constructor has no arguments then it is called constructor without parameters.

#include <iostream>
#include <iostream.h>
#include <conio.h>
class myclass {
int a,b;
public:
myclass(); // constructor
~myclass(); // destructor
void show();
};
myclass::myclass(){
cout << "In constructor\n";
a = 10;
b = 20;
}
void myclass::show()
{
cout << "A =" << a << endl << "B =" << b << endl;
cout << "Sum is " << a+b << endl;
}
void main()
{
clrscr();
myclass ob;
ob.show(); }

Constructor with parameters (or) parameterized constructor


If a constructor has arguments then it is called parameterized constructor. The value of the
arguments should be given along the object declaration. The general form is:

Classname object( argument_list );


(or)
Classname object = classname(argument_value_list);
Example:
#include <iostream>
#include <iostream.h>
#include <conio.h>
class myclass {
int a,b;
public:
myclass(int x, int y); // constructor
~myclass(); // destructor
void show();
};
myclass::myclass(int x, int y) {
cout << "In constructor\n";
a = x;
b = y;
}
void myclass::show() {
cout << "A =" << a << endl << "B =" << b << endl;
cout << "Sum is " << a+b << endl;
}
void main()
{
clrscr();
myclass ob(10,20);
ob.show();
}
Multiple Constructor (or) Constructor Overloading
If a class has more than one constructor, then it is called multiple constructors. This technique
is called overloading constructors, because all constructors have the same name and they
differ only in the number of arguments or data types.
Example:
#include<iostream.h>
#include<conio.h>
class con
{
int c;
public:
con();
con(int x);
con(int x,int y);
con(int x,int y,int z);
};
con ::con() {
c=0;
cout<<"\n\n\t Result is :\t"<<c;
}
con ::con(int x) {
c=x*x;
cout<<"\n\n\t Result is :\t"<<c;
}
con::con(int x,int y)
{
c=x*y;
cout<<"\n\n\t Result is :\t"<<c;
}
con ::con(int x,int y,int z)
{
c=x*y*z;
cout<<"\n\n\t Result is :\t"<<c;
}
void main()
{
clrscr();
cout<<"\n\n\t OUTPUT:\n";
con c;
con s(3);
con s1(3,5);
con s2(3,2,2);
getch();
}
Constructor with default arguments
If we give initial values to the member variables inside the argument list of constructor then it
is called constructor with default arguments. The general form is:

constructor_name (return_type variable1= value1, return_type variable2=


value2, …. return_type variable n= value n
{
member_variable1 = variable1;
member_variable2 = variable2
……..
member_variable n = variable n;
}
At the time of object declaration, depending upon the value, the constructor automatically
assign the values to member variables. If any value is missing this will be taken from the
argument list values.
Example:
#include <iostream>
#include <iostream.h>
#include <conio.h>
class myclass {
int a,b;
public:
myclass(int x, int y); // constructor
~myclass(); // destructor
void show();
};
myclass::myclass(int x = 30, int y = 40){
cout << "In constructor\n";
a = x;
b = y;
}
void myclass::show() {
cout << "A =" << a << endl << "B =" << b << endl;
cout << "Sum is " << a+b << endl;
}
void main()
{
clrscr();
myclass ob1(10,20);
myclass ob2(5);
ob1.show();
ob2.show();
}
Output:
A = 10
B = 20
Sum is 30
A=5
B = 40
Sum is 45

1.14. Operator Overloading


An operator function defines the operations that the overloaded operator will perform relative
to the class upon which it will work. An operator function is created using the keyword
operator.
Creating a Member Operator Function
A member operator function takes this general form:
ret-type class-name::operator#(arg-list)
{
// operations
}
The # is a placeholder. When you create an operator function, substitute the operator for the
#. For example, if you are overloading the / operator, use operator/. When you are
overloading a unary operator, arg-list will be empty. When we are overloading binary
operators, arg-list will contain one parameter.
Example:
#include <iostream>
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
loc operator+(loc op2);
};
// Overload + for loc.
loc loc::operator+(loc op2)
{
loc temp;
temp.longitude = op2.longitude + longitude;
temp.latitude = op2.latitude + latitude;
return temp;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1.show(); // displays 10 20
ob2.show(); // displays 5 30
ob1 = ob1 + ob2;
ob1.show(); // displays 15 50
return 0;
}
Here the operator+() function returned some other type, this expression would not have been
valid:
ob1 = ob1 + ob2;
In order for the sum of ob1 and ob2 to be assigned to ob1, the outcome of that operation must
be an object of type loc.

Operator Overloading Using a Friend Function


Since a friend function is not a member of the class, it does not have a this pointer. Therefore,
an overloaded friend operator function is passed the operands explicitly. This means that a
friend function that overloads a binary operator has two parameters, and a friend function that
overloads a unary operator has one parameter. When overloading a binary operator using a
friend function, the left operand is passed in the first parameter and the right operand is
passed in the second parameter.
In this program, the operator+() function is made into a friend:
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {} // needed to construct temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
friend loc operator+(loc op1, loc op2); // now a friend
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};
// Now, + is overloaded using friend function.
loc operator+(loc op1, loc op2) {
loc temp;
temp.longitude = op1.longitude + op2.longitude;
temp.latitude = op1.latitude + op2.latitude;
return temp;
}
// Overload - for loc.
loc loc::operator-(loc op2) {
loc temp;
// notice order of operands
temp.longitude = longitude - op2.longitude;
temp.latitude = latitude - op2.latitude;
return temp;
}
// Overload assignment for loc.
loc loc::operator=(loc op2) {
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Overload ++ for loc.
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
}
There are some restrictions that apply to friend operator functions. First, you may not
overload the =, ( ), [ ], or –> operators by using a friend function. Second, as explained in the
next section, when overloading the increment or decrement operators, you will need to use a
reference parameter when using a friend function.

Using a Friend to Overload ++ or – –


If we want to use a friend function to overload the increment or decrement operators, you
must pass the operand as a reference parameter. This is because friend functions do not have
this pointers.

#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
loc operator=(loc op2);
friend loc operator++(loc &op);
friend loc operator--(loc &op);
};
// Overload assignment for loc.
loc loc::operator=(loc op2) {
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that generated call
}
// Now a friend; use a reference parameter.
loc operator++(loc &op) {
op.longitude++;
op.latitude++;
return op;
}
// Make op-- a friend; use reference.
loc operator--(loc &op) {
op.longitude--;
op.latitude--;
return op;
}
int main()
{
loc ob1(10, 20), ob2;
ob1.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob2.show(); // displays 12 22
--ob2;
ob2.show(); // displays 11 21
return 0;
}

If we want to overload the postfix versions of the increment and decrement operators using a
friend, simply specify a second, dummy integer parameter. For example, this shows the
prototype for the friend, postfix version of the increment operator relative to loc.
// friend, postfix version of ++
friend loc operator++(loc &op, int x);

1. What is meant by operator overloading?


2. Which operators can not be overloaded?
Overloading new and delete
It is possible to overload new and delete. You might choose to do this if you want to use
some special allocation method. For example, you may want allocation routines that
automatically begin using a disk file as virtual memory when the heap has been exhausted.
Whatever the reason, it is a very simple matter to overload these operators. The skeletons for
the functions that overload new and delete are shown here:
// Allocate an object.
void *operator new(size_t size)
{
/* Perform allocation. Throw bad_alloc on failure.
Constructor called automatically. */
return pointer_to_memory;
}
// Delete an object.
void operator delete(void *p)
{
/* Free memory pointed to by p.
Destructor called automatically. */
}
The type size_t is a defined type capable of containing the largest single piece of memory that
can be allocated. (size_t is essentially an unsigned integer.) The parameter size will contain
the number of bytes needed to hold the object being allocated. This is the amount of memory
that our version of new must allocate.
The overloaded new function must return a pointer to the memory that it allocates, or throw a
bad_alloc exception if an allocation error occurs. Beyond these constraints, the overloaded
new function can do anything else you require. When you allocate an object using new
(whether your own version or not), the object's constructor is automatically called.
The delete function receives a pointer to the region of memory to be freed. It then releases the
previously allocated memory back to the system. When an object is deleted, its destructor
function is automatically called.
Example
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
void *operator new(size_t size);
void operator delete(void *p);
};
// new overloaded relative to loc.
void *loc::operator new(size_t size) {
void *p;
cout << "In overloaded new.\n";
p = malloc(size);
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}
// delete overloaded relative to loc.
void loc::operator delete(void *p)
{
cout << "In overloaded delete.\n";
free(p);
}
int main()
{
loc *p1, *p2;
try {
p1 = new loc (10, 20);
} catch (bad_alloc xa) {
cout << "Allocation error for p1.\n";
return 1;
}
try {
p2 = new loc (-10, -20);
} catch (bad_alloc xa) {
cout << "Allocation error for p2.\n";
return 1;;
}
p1->show();
p2->show();
delete p1;
delete p2;
return 0;
}
Output from this program is.
In overloaded new.
In overloaded new.
10 20
-10 -20
In overloaded delete.
In overloaded delete.

PART-A (2 MARKS)
1. Write any four features of OOPS.
2. What are the Basic concepts of OOS?
3. Define objects.
4. Define class.
5. Give any four advantages of OOPS.
6. Give any four applications of OOPS.
7. Give any four applications of c++.
8. Define tokens.
9. What is keyword?
10. Rules for naming the identifiers in C++.
11. What is a scope resolution operator?
12. What do you mean by enumerated data type?
13. What are symbolic constants?
14. What do you mean by dynamic initialization of variables?
15. What are reference variable?
16. Define constructor.
17. Define default constructor.
18. Define parameterized constructor.
19. Define default argument constructor.
20. What is the ambiguity between default constructor and default argument constructor?
21. Define copy constructor.
22. Define dynamic constructor.
23. Define const object.
24. Define destructor.
25. Define multiple constructors.
26. Write some special characteristics of constructor
27. Which operators cannot be overloaded?
28. What is meant by operator overloading?

PART-B (16 MARKS)


1. Explain with the Basic Concepts of object oriented programming.
(a) Explain the elements of object oriented programming. (8)
(b) What are the difference between reference variables and normal variables? Why
cannot a
2. Can constant value be initialized to variables of reference type? (8)
3. Explain about call-by-reference and pointer types with program.
(a) Describe the advantages of OOP. (8)
(b) What are the difference between pointers to constants and constant to
pointers? (8)
(a) Describe the applications of OOP technology. (8)
(b) What is function invocation? Explain briefly with program. (8)
1. Explain about Data Handling and member function. Explain copy constructor and
destructor with suitable C++ coding
2. Explain operator overloading with an example.
3. How do you overload the operators ‘new’ and ‘delete’? Give a sample program to
implement both.
4. Discuss about the constructor overloading in detail. Give an example to implement it.
5. Discuss about various types of constructors in detail. Give some examples.

-----------------------------------------------

You might also like