Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 39

INTRODUCTION TO CPP

PROGRAM: is defined as set of instructions

PROGRAMMING: is the art of writing programs.

PROGRAMMING METHODOLOGIES are classified into 2 types:

1. PROCEDURE ORIENTED PROGRAMMING (POP)


2. OBJECT ORIENTED PROGRAMMING (OOP)

Procedure oriented programming Vs. Object oriented programming

 In POP, importance is given to the sequence of things to be done i.e.


algorithms and in OOP, importance is given to the data. 
 In POP, larger programs are divided into functions and in OOP, larger
programs are divided into objects. 
 POP follows a top down approach in problem solving while OOP follows a
bottom up approach.
  In POP, there is no access specifier and in OOP there are public, private
and protected specifier. 
 In POP, operator cannot be overloaded and in OOP operator can be
overloaded.
  In POP, Data moves openly around the system from function to function,
In OOP objects communicate with each other through member functions 
 COBOL, PASCAL, C, FORTRAN are some of the examples of POP
languages.
 C++, JAVA are some of the examples of OOP languages.

Advantages of POP:

 Easy to read the code since functions are used and also it is easy to
debug the code.

Disadvantages of POP:

 Code reusability is not permitted.


 No security for global data.
 Since no code reusability is there, the size of program will keep on
increasing. As a result at a particular point the programmer looses
the control over the code that is, flow of execution of code cannot be
understood.

1
Benefits of OOPL:

 Inheritance can eliminate redundancy of code and provide


reusability.
 Data hiding helps to built secure programs
 Easy to partition a task into object
 Data central design approach enables us to capture more details of
a model in implemented form.

Why we go for OOPS…?

Because this is an implementation over structure programming.

Advantages of OOPS:

 Extendibility increases
 Reusability increases

HISTORY OF C++ :

C++ is an Object Oriented Programming Language. It


was developed by Bjarne Stroustrup   at AT and T Bell
Labs during 1980’s. C++ is an extension of C with major
addition of all object oriented features. Stroustrup
initially called C++ as "C with Classes". C++ is a
suoperset of C. therefore all the programs in C are also
written in C++. He had combined the Simula 's use of
classes and object-oriented features with the power and
efficiency of C. The term C++ was first used in 1983.

2
PROPERTIES OF OOPS
1) OBJECT
2) CLASS
3) ABSTRACTION
4) ENCAPSULATION
5) INHERITANCE
6) POLYMORPHISM
7) DYNAMIC BINDING
8) MESSAGE PASSING

OBJECT:

 Anything that exists in the real world is said to be object


 An object may be a name of person, place or thing etc.,,
 Every object will have some property and behavior.
 Object is a variable of type class.

CLASS:
 Class is a collection of objects
 Class is a common name given to a group of objects
 For example: IT is name of class. Each and every student present in
IT class is said to be a object.
 In computer terminology class is called as collection of data and
functions.
 Properties of object are represented by data (variables)
 Behaviour of object is represented by functions of the class.

Example:

1. Consider “student” as object

Properties of student: name, roll no, marks, height.weight, gender,color


etc.,,

Behavior of student: writing, reading, listening etc.,,

2.

objects class
Apple, mango,grapes,orange etc.,, fruit
Pink,blue,black,yellow etc.,, color

3
DATA ABSTRACTION:

 The act of representing essential features with out including back


ground details (Hiding the actual content and showing only the
required content is said to be abstraction).
 Example: index of text book, google search engine etc.,,
 Advantage of abstraction is every user will get his/her own view of
the data.

DATA ENCAPSULATION:

 Wrapping (combining) up of data and function into a single unit is


called as encapsulation.
 Data will be not accessible to external classes. Only those functions
that are present in that class can access that data.

INHERITANCE:

 One class using the properties of another class is said to be


inheritance. Ex: parents - children
 Code reusability is achieved through inheritance
 Class whose properties are used by other class is called as BASE
CLASS.
 Class which uses the properties of other class is said to be
DERIVED CLASS.

PLOYMORPHISM

 Ability to take more than one form is said to be polymorphism.


 POLY means MANY
 MORPHISM means FORMS
 Example:

I. + is used for addition and concatination


II. * is used for multiplication and also for declaring a pointer variable
III. >> and << are used for right and left shift of bit operations and
also along with cin and cout in CPP.

4
DYNAMIC BINDING

 Link between function call and function procedure is made at run-


time.
 Dynamic binding is also called as late binding or run-time binding.

MESSAGE PASSING:

 In OOP, set of objects communicate with each other.

Structure of C++:

1. Include files
2. Class declaration
3. Member functions
4. Definitions
5. Main function program

COUT & CIN

 cout is used to print data on the screen.


 cin is used to accept values at run-time.

//Simple Program ( Program to add two integers )

#include<iostream>
using namespace std;
main()
{
int a,b,c;
cout<<"enter 2 integers";
cin>>a>>b;
cout<<(a+b);
}

Note:

5
Iostream file : This directive causes the pre-processor to add the
contents of iostream to the program . it contains declaration for
identifiers. Cout and operator << and cin and operator >>.

 Using >> or << more than one time in a statement is known as


CASCADING.
 Example: cout<<a<<b; or cin>>a>>b;

 << is called as insertion operator, which is used to insert values


on the console( output screen)

 >> is called as extraction operator, which is used to extract


values from key board

 DATA TYPES, VARIABLES, KEYWORDS, CONTROL STRUCTURES,


OPERATORS etc.,, which are used in C are also applicable in CPP
also.

 Apart from the 32 keywords in C we have some more keywords in


CPP.

6
INLINE FUNCTION:

An inline is a function i.e, expanded in line when it is invoked


(called) i.e., the compiler replaces the function call with the
corresponding function code.
Syntax :

inline datatyope function name(arg list)


{
Block of statements;
}

Example:
#include<iostream>
using namespace std;

inline square(int h)
{
return h*h;
}

main()
{
cout<< square(5);
}

output: 25

 In the above code when function call is made that is when square(5) is
executed by compiler the function definition will be replaces the
function call.
 This happens when a function is preceded by the keyword “inline”
 Advantage of inline function is that control of the program will be
with main() only.
 Disadvantage is for each function call a separate copy of function
definition is created in memory.

Note:
 Inline function may not work if it contains any loop
(s),switch,goto,static varibles.
 Inline function cant be recurive.
 member function defined inside the class are inline

7
REFERENCE VARIABLE

 A variable which is used to provide an alternative name for a


previously defined variable is called as REFERENCE VARIABLE.
 reference is a substitute for an object.
 (ampersand) & operator is used before the name of the variable.

Syntax : datatype &referencevar_name=var_name;

Example:
int x=10;
int &y=x;
cout<<x; //10
cout<<y; //10

REFERENCE TO A REFERNCE:
int x=10;
int &y=x;
int &m=y;
int &k=m;
cout<<x; //10
cout<<y; //10
cout<<m; //10
cout<<k //10
it is not possible to assign a different value for a reference
variable

Achieving Call by reference through reference parameter (variable):

Void function( int &);


main()
{
int a=20;
function(a);
cout<<a;
}
void function ( int &b) // b is pointing to the same location where a points
{
b=b+10; output:
} 30

8
UNARY SCOPE RESOLUTION OPERATOR (::)

 If the name of local and global variables is same then to differentiate


both of them we use unary scope resolution operator.
 Scope resolution operator is denoted by ::

Using unary scope resoulation operator, we can able to access


the global variables when they have been hidden by the local
variables of the same name in local scope.

Syntax : :: VariableName ;

Example:

#include<iostream>
using namespace std;
int m=10; //global variable
main()
{
int m=20;
cout<<m; //20
cout<< ::m; //10
}

 In the above ‘m’ is decalred as both local and global variable.


 ‘m’ refers to local value that is 20.
 ‘::m’ refers to global value that is 10.

9
OVERLOADING: It refers to the use of same task for different
purposes.

FUNCTION OVERLOADING

 Functions having same name differ by number and type of


arguments is called function overloading.

 Function overloading is using same function name multiple times


with in the same program but with different parameters. Complier
differentiates which function is to be called depending upon:
1. The number of arguments/parameters.
2. Type of argument
3. Return type of function.

Program to demonstrate function overloading:


#include<iostream>
using namespace std;
void area()
{
cout<<"I will calculate\n ";
}

void area(int x)
{
cout<<”square area” <<x*x<<endl;
}

void area(int p,int q)


{
cout<<”rectangle area is”<<p*q<<endl;
}

void area(float a,float b)


{
cout<<”float value is”<<a*b<<endl;
}

main()
{
area();
area(2,3);
area(2);
area(2.6f,3.6f);
}

10
ADVANTAGES OF FUNCTION OVERLOADING ARE:

 Different values can be passed to same function


 For a programmmer it will be easy to remember the same function
name every time.

NOTE:
 Function overloading should be done with caution. That is we should
not overload function that are not related to each other.
 Also if we are using classes and objects in function overloading then
all the functions should be present in the same class.
 Functions of different classes cannot be overloaded.

TEMPLATES

 Template is a mechanism that makes one function or class to handle


many kinds of data types.
 When templates are used with functions they are function templates
 When templates are used with classes they are class templates or
generic classes.

Function Template:
If a program logic and operations are identical for each data type, this
may be performed more conveniently using function templates. All
function template definition begins with the keyword template
followed by list of formal type parameters to the function template
enclosed in <>. Every formal parameter is preceded by keyword class
or type name.

Program to demonstrate function templates

#include <iostream.h>
template <class T>
T max(T &a, T &b)
{
if(a>b)
return a;
else
return b;
}

11
main()
{
cout << max(10, 20);
cout << max(‘v’,’m’);
cout << max(3.5f,4.5f);
}
 After seeing a function template compiler remembers it for future use.
 Compiler will not generate any code using function template since it
don’t know that kind of data it is going to handle.
 When a function call is made depending on the type of values passed
compiler substitutes that data type in place of ‘T’ in the function
template.

Program to demonstrate class templates (bubble sort)


#include<iostream>
using namespace std;

template<class t>
class bubble
{
t a[20];
public:
void get(int);
void sort(int);
void display(int);
};
template<class t>
void bubble<t>::get(int n)
{
cout<<"enter elements";
for(int i=0;i<n;i++)
cin>>a[i];
}
template<class t>
void bubble<t>::display(int n)
{
cout<<"sorted array is";
for(iint i=0;i<n;i++)
cout<<a[i];
}

12
template<class t>
void bubble<t>::sort(int n)
{
t temp;
for(int i=0; i<n; i++)
for(int j=0;j<n-1;j++)
if(a[j] > a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

main()
{
bubble<int> b1;
cout<<"integer sorting";
b1.get(5);
b1.sort(5);
b1.display(5);

bubble<char> b2;
cout<<"character sorting";
b2.get(5);
b2.sort(5);
b2.display(5);
}

 We can use multiple parameters in both class and function templates


 A specific class created from a class template is called as template
class and the process of creating a template class is known as
INSTANTIATION.
 Template functions can also be overloaded.

13
CLASSES AND DATA ABSTRACTION:

CLASS AND OBJECT:

 Class is similar to the concept of user-defined data type.


 Class can also be called as collection of objects.
 Object is a variable of type class.

SYNTAX TO DECLARE CLASS IS:


class class_name
{
private: var_declaration;
function declaration;
public: var_declaration;
function declaration;
protected: var_declaration;
function declaration;
};
 private, public and protected are access specifiers or visibility
labels.
 Private members can be accessed only with in class and functions of
that class
 Public members can be accessed anywhere in the program
 Protected members can be accessed by a class and its derived class,
and also by the derived class of the derived class.

SYNTAX TO DECALRE OBJECT IS:


Class_name object_name;

TO ACCESS MEMBERS OF CLASS:

Object_name.function();

14
Program to find average of 3 numbers using the concept of class,
object and member function
#include<iostream>
using namespace std;
class demo
{
private:
int x,y,z;
float k;
public:
void input(int,int,int);
void output();
void average();
};

void demo::input(int p,int q,int r)


{
x=p; y=q; z=r;
}

void demo::output()
{
cout<<k;
}

void demo::average()
{
k=(x+y+z)/3;
}

main()
{
demo d;
d.input(10,20,30);
d.average();
d.output();
}
 A function can be defined either inside or outside the class.
 If it is defined outside then:
It should be written along with its class name and ::

15
Scope Rules:

Class Scope: Data members and member functions of a class belongs


to the class scope.
File Scope: Non-member functions will have file scope.
Function Scope: Variable defined in a member function has function
scope. i.e.., they are known to that function.

Note:
If a member function defines a variable with the same name as a
variable with the class scope, the class scope variable is hidden by
function scope variable in the function scope such variable can be
accessed by class name::variable name
Example: (refer class notes)

Initializing Class Objects:

CONSTRUCTOR

 In c-language values will be passed through function call as:


function_name(arguments);
 In cpp it is done as follows:
Values are passed by calling the function along with object name.
 In c-language variables are initialized at the time of declaration itself.
 That is, int x =10;
 In the same way, in order to enable an object to pass values at the
time of its creation only, we use a special member function called as
CONSTRUCTOR.

 Constructor is a special member function that is called


automatically when an object is created to a class.

PROPERTIES OF CONSTRUCTOR:
 Name of the constructor function is same as class name
 It has no return type not even void
 There is no private constructor i.e., Constructor must be public.
 Constructor may or may not have parameters.
 Constructor cannot return a value.
 Constructor cannot be friend function to any other class.

16
 Syntax of constructor is:
class_name()
{
….
….}

 Types of constructors are:

1. Default constructor
 When a class is created then compiler automatically allocates a
constructor called as default constructor. (A class can contain only
one default constructor i.e default constructor cannot be
overloaded)
2. Non-parameterized constructor
 Constructor with no parameters
3. Parameterized constructor
 Constructor with parameters. (We can pass arguments to
constructor while creating the object within the parenthesis beside
object)
4. Copy constructor
 Passing object as an argument.
 That is initializing object of one class with other object of same
class is called copy initialization.
 Such a constructor is called as copy constructor

Rules for copy constructor:


 It can have only one parameter
 It must be reference parameter
 Parameter type must be same as class name.

OVERLOADING OF CONSTRUCTOR MEANS GIVING A


DIFFERENT MEANING TO THE CONSTRUCTOR.

Multiple Constructor: (Overloading Constructors)


That is more than one constructor can be defined for a class.

17
Program for Constructor Overloading

#include<iostream>
using namespace std;
class abc
{
private: int a,b;

public:
abc( )
{
cout<<”default constructor \n”;
a=10;
b=20;
}

abc( int x, int y)


{
cout<<”parameterized constructor \n”;
a=x;
b=y;
}

abc(abc &i)
{
cout<<”copy constructor \n”;
a=i.a;
b=i.b;
}

void diaplay()
{
cout<<”a”<<a<<”b”<<b<<endl;
}
}
main()
{
abc ob1;

18
abc ob2(30,40);
abc ob3(ob2);
ob1.display();
ob2.display();
ob3.display();
}

Output:
a 10 b 10
a 30 b 40
a 30 b 40

DESTRUCTOR

Destructor is a member function which is automatically called


when an object of the class is destroyed or terminated.

Syntax : ~class_name()
{
}

Note:

 The destructor function also has the same name as a class but
preceded by tilde(~) character.
 The name of the destructor for a class is a tilde followed by the
class name.
 Class destructor is called when an object is destroyed.
 A destructor freezes the memory occupied by the object so that it
can be reused to hold new object.
 Destructor is declared in the public section of a class
 Destructor receives no parameters and no return value.
 Destructor cannot be overloaded.

MAIN DIFFERENCE BETWEEN CONSTRUCTOR AND


DESTRUCTOR:
While a class can have multiple constructors but can have only one
destructor.

19
Default constructor cannot be overloaded.

Program to demonstrate destructor


Ex:1

#include<iostream>
using namespace std;

class abc
{
public:
abc()
{
cout<<”constructor is called\n”;
}
~abc()
{
cout<<”destructor is called\n”;
}
};

main( )
{
abc ob1;
}

Output:
Constructor is called
Destructor is called

20
Program to demonstrate destructor
Ex:2

#include<iostream>
using namespace std;
int c=0;
class abc
{
public:
abc()
{
c++;
cout<<" object"<<c<<”is created\n”;
}
~abc()
{
cout<<"object"<<c<<”is destroyed\n”;
c--;
}
};
main()
{
cout<<" In main";
abc a1,a2;
{
cout<<"block-1";
abc a3;
}
}

Output:
In main
Object 1 is created
Object 2 is created
Object 3 is created
Object 3 is destroyed
Object 2 is destroyed
Object 1 is destroyed

21
FRIEND FUNCTION

[ Generally in C++, only public functions have right to access private


variables of the class. In addition C++ has one more function to
access private variables of the same class even outside the class. ]

 “friend” is a keyword.
 Friend function is used to access the private data of the class.
 Friend function takes object of a class as an argument
 Friend function cannot refer members of class directly. It uses the
object to refer them
 Friend function cannot be called using object of class, it should be
called directly.
 Normal values cannot be passed as arguments in friend function.

A friend function of a class is defined outside the class scope and yet
has right to access private members of the class.
A function or entire class may be declared to be a friend of another
class.
To declare a function as a friend of a class receive the function
prototype in class declaration with friend keyword.
Syntax:

friend datatype functionname( );

Friend function is not a member function of the class. i.e., it is a non-


member function.

Characteristics:

It is not in the scope of the class to which it has been declared as friend.
It cannot be called using the object of the class.
It can be called like a normal function without the help of any object.
It can be declared either in public or private part of the class.
It has an object as an argument.

22
Program to demonstrate friend function
#include<iostream>
using namespace std;

class sample
{
private:
int m1,m2,m3;
public:
void getmarks();
friend void total(sample );
};

void sample:: getmarks()


{
cout<<”enter m1 m2 m3 marks\n”;
cin>>m1>>m2>>m3;
}

Int total(sample s)
{
return (s.nm1+s.m2+s.m3);
}

main()
{
sample e;
e.getmarks();
cout<<”total marks “<<total(e);
}

Output:
enter m1 m2 m3 marks
90 80 70
total marks 240

23
“this” POINTER

“this” is a pointer that points to the object for which the


member function is called.
or
 “this” pointer is used to represent an object that invokes a member
function.

Program to demonstrate “this” pointer

#include<iostream>
using namespace std;
class abc
{
int x;
public:
abc()
{
x=10;
}
void function(int x)
{
cout<< x;//20
cout<< this->x;//10
}
};

main()
{
abc a1;
a1.function(20);
}

Output: 20
10

24
Application of ‘this’ pointer:
 To return the object to which it points to.
 To compare two or more objects inside a member function and
return the invoking object as a result.

Program to find maximum of 2 numbers using “this” pointer

#include<iostream>
using namespace std;
class max
{
int a;
public:
void get()
{
cout<<"enter a";
cin>>a;
}

void compare(max m)
{
if(this->a > m.a)
cout<<"max no. is"<<this->a;
else
cout<<"max no. is"<<x.a;
}
};
main()
{
max p,q;
p.get();
q.get();
p.compare(q);
}
Out put:
Enter a 10

25
Enter a 20
Max no. is 20
Dynamic Memory Allocation:

C++ provides two dynamic allocation operators: new and delete. These
operators are used to allocate and free memory at run time.

C++ also supports dynamic memory allocation functions, called malloc() and
free().
.
The new operator allocates memory and returns a pointer to the start of it.
The delete operator frees memory previously allocated using new.

The general forms of new and delete are shown here:

Datatype *variable = new datatype;

delete variable;

Here,variable is a pointer variable that receives a pointer to memory that is


large enough to hold an item of type type.

main()
{
int *p = new int; // allocates memory( space ) for an int
*p = 100;
cout << "At " << p << " ";
cout << "is the value " << *p << "\n";
delete p; // deallocates memory for variable p
}

Allocating for Arrays:

You can allocate arrays using new by using this general form:

Datatype * variable =new datatype [size];

Here, size specifies the number of elements in the array.


To free an array, use this form of delete:

delete [ ] variable;

Here, the [ ] informs delete that an array is being released.

26
In C language we are provided with dynamic memory allocation functions
like malloc(),calloc(),free().

For Allocating memory at run time:


malloc(): allocate memory dynamically at run time

Syntax:
Data type *variable = (datatype *) malloc( sizeof(datatype) );

Ex: int *p = (int *) malloc( sizeof(int) );

For Arrays:
Calloc(): allocates memory dynamically at run time

Syntax:
Data type *variable = (datatype *) calloc(n, sizeof(datatype) );
Where: n is size of array.

Ex: int *p = (int *)calloc( 10,sizeof(int) ); // which allocates 20 bytes for the
variable p at run time.

For De-Allocation:
free(): Deallocate memory at run time.
Syntax:
free(variable name);
Ex: free(p);

27
DYNAMIC MEMORY ALLOCATION

int x[10];

 For the above statement 20 bytes of memory is allocated (10*2 bytes)


 This memory is allocated when that statement is executed by compiler
 This type of allocation is known as STATIC MEMORY ALLOCATION.
 But in this kind of declaration the memory might be wasted.
 That is, in the above declaration 20 bytes of memory is allocated for
10 elements, but if we assign only 2 elements that is only 4 bytes of
memory is being used, thereby wasting 16 bytes of total memory.
 In order to avoid this we go for the concept of DYNAMIC MEMORY
ALLOCATION.

Allocation memory at run-time is called as dynamic memory


allocation
 OPERATORS USED FOR DYNAMIC MEMORY ALLOCATION ARE:
 new
 delete

 “new” operator ised to allocate memory at run-time


 Syntax for new operator is:
datatype *pointer_variable = new datatype[size];

 “delete” operator is used to de-allocate memory at run-time.

Syntax for delete operator is:


delete[size] pointer_variable;

28
PROGRAM FOR DYNAMIC MEMORY ALLOCATION

#include<iostream>
using namespace std;
main()
{
int size,i;
cout<<"enter array size";
cin>>size;

int *p = new int[5];

cout"<<"enter elements";
for(i=0;i<size;i++)
cin>>p[i];
cout<<"elements are";
for(i=0;i<size;i++)
cout<<p[i];

delete [ ]p;
}

 ‘p’ acts as a constant pointer


 It holds the address of memory allocated.
 Delete operator is used because to free memory that is allocated at
run-time.
 If we don’t use delete then that particular memory space cannot be
used by other variables.
 Both in compile-time and run-time memory allocation after closing
program memory is cleared.
In compile time allocation memory is automatically cleared, where as
in run-time allocation memory should be cleared by using “delete”
operator

29
CONSTANT OBJECTS AND CONSTANT MEMBER FUNCTIONS

 If we don’t want to modify value of some object then we can use the
keyword “const”.
 If a member function does not modify any data member in the class
then we can declare it as “const” member function.
 A “const” object can call only constant member function.
 A non-const object can call both const member function and non-
const member function.

Program to demonstrate const object and member function


#include<iostream>
using namespace std;
class demo
{
int x,y;
public:
demo()
{
x=0;
y=0;
}

demo(int p,int q)
{
x=p;
y=q;
}

vois show() const


{
cout<<x;
cout<<y;
}

void display()
{
cout<<"hello";

30
}
};
main()
{
demo d1;
const demo d2(20,40);
d1.show();
d2.show();
d1.display();
d2.display();// error
}

31
STATIC VARIABLES AND STATIC MEMBER FUNCTIONS

 When you precede a member variable's declaration with static, you


are telling the compiler that only one copy of that variable will exist
and that all objects of the class will share that variable.

 Unlike regular data members, individual copies of a static member


variable are not made for each object.

 No matter how many objects of a class are created, only one copy of a
static data member exists. Thus, all objects of that class use that
same variable.

 All static variables are initialized to zero before the first object is
created.

 When you declare a static data member within a class, you are not
defining it. (That is, you are not allocating storage for it.)

 Instead, you must provide a global definition for it elsewhere, outside


the class. This is done by re declaring the static variable using the
scope resolution operator to identify the class to which it belongs.
This causes storage for the variable to be allocated. (Remember, a
class declaration is simply a logical construct that does not have
physical reality.)

To understand the usage and effect of a static data member,


consider this program:

#include<iostream>
using namespace std;
class A
{
public:
static int count;
A()
{
count++;
}
};

32
int A::count;
main()
{
A a1,a2,a3;
cout<<"objects created "<<a1.count;
A a4,a5;
cout<<"objects created "<<A::count;
}

output:
objects created 3
objects created 5

Static Member Functions

 Member functions may also be declared as static.


 There are several restrictions placed on static member functions.
 They may only directly refer to other static members of the class. (Of
course, global functions and data may be accessed by static member
functions.)
 A static member function does not have a ‘this’ pointer.
 A static member function may not be ‘virtual’.
 They cannot be declared as const.

Consider the following program

#include<iostream>
using namespace std;
class A
{
public:
static int x,y;
A()
{
x++; y=5;
}
void static put();

33
};

void A::put()
{
cout<<x;
cout<<y;
}
int A::x;
main()
{
A p,q,r;
p.put();
A s,t;
A::put();
}

Output: 3 5

34
OPERATOR OVERLOADING

 The mechanism of giving a different meaning to an operator is known


as operator overloading.
 Operator overloading is done by using a special member function
called as “OPERATOR” function.

Syntax of operator function:


return_type classname:: operator op(arguments)
{
Block of Statements;
}
 op means the operator that is to be overloaded.

 Types of operators which can be overloaded are:


1. Unary operators
2. Binary operators
3. Special operators
4. Insertion and extraction operators

 Unary operators are operators that act upon only single operand.
Example: ++, - -, -
 Binary operators are operators acting upon two operands
Example: +, /.%,<,> etc.,
 Operators like new,delete,(,),[,] etc., are special operators.
 >> and << are extraction and insertion operators.

The operations which cannot be overloaded are:


1. Scope resolution operator (::)
2. Ternary operator(?:)
3. Size of operator
4. Member access operator(.)
5. Indirection operator(.*)

35
PROGRAM FOR UNARY OPERATOR OVERLOADING

#include<iostream>
using namespace std;
class unary
{
int a,b;
public:
void get();
void display();
void operator -();
};

void unary::get()
{
cout<<"enter the values of a and b"<<"\n";
cin>>a>>b;
}
void unary:: display()
{
cout<<"a= "<<a<<" ,b= "<<b<<endl;
}

void unary::operator -()


{
a=-a;
b=-b;
}
main()
{
unary u1;
u1.get();
u1.display();
-u1;
u1.display();
}

36
PROGRAM FOR CREATION OF COMPLEX CLASS WITH
OPERATOR OVERLOADING (binary operator overloading)

#include<iostream>
using namespace std;
class complex
{
float x,y;
public:

complex()
{
x=0;
y=0;
}

complex( float r, float i)


{
x=r;
y=i;
}

complex operator +(complex);

void display()
{
cout<<x<<" "<<y<<endl;
}
};

complex complex:: operator +(complex C)


{
complex t;
t.x=x+C.x;
t.y=y+C.y;
return(t);
}

37
main()
{
complex c1(2.6,3.6),c2(4.6,5.6),c3;
c3=c1+c2;
c1. display();
c2.display();
c3.display();
}

RULES FOR OPERATOR OVERLOADING

 Only existing opearators can be overloaded.New opearators can not be


created

 the overload opearator must have at least on operand that is of user


defined type

 we can not change the basic meaning of an operator i.e we can not use +
for subtraction

 overload operators follow the syntax rules of the orginal opearators.they


cannot be overriden.

 sizeof,.(membership opearator),. *(pointer to member opearator) ,:: (scope


resolution operator),?: (conditional operator) can’t be overloaded.

 =(assignment operator), ()(function call operator),[] (subscripting


operator),-> (class member access operator) can’t be overloaded using
friend functions.

 Unary operators,overloaded by means of a member function take no


explicit arguments and return no explicit values,but, those overloaded by
means of a friend function, take one referenece argument(the object of
the relvant class).

 Binary operators overloaded through a member function function take


one explicit argument and those which are overloaded through a friend
function take 2 explicit arguments.

 When using binary operators overloaded through a member function, the


left hand operand must be an object of the relvant class.

 Binary arithmetic operator such as +,-,*,and / must explicitly return a


value.They must not attempt to change their own arguments.

38
 Operator overloading can be done using friend function also

39

You might also like