0% found this document useful (0 votes)
7 views16 pages

Unit 2 Notes

Uploaded by

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

Unit 2 Notes

Uploaded by

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

21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

UNIT 2
METHODS AND POLYMORPHISM

Constructors- Types of constructors - Static constructor and Copy constructor -Destructor -


Polymorphism: Constructor overloading - Method Overloading Operator Overloading - UML
Interaction Diagrams -Sequence Diagram - Collaboration Diagram - Example Diagram.

=======================================================================
CONSTRUCTOR
• A Constructor is a special member function whose task is to initialize the objects of its class.
Its name is same as the class name.
• The Constructor is invoked automatically whenever an object of its associated class is
created.
• It is called Constructor because it constructs the values of data members of the class.
Syntax:
class classname
{
public:
class name( args)
{
// Constructor body definition
}
};

Example:
class student
{
int regno;
char name[10];
public:
student( ) //constructor declared
{
regno=08; name=”Geetha”;
}
};

Rules For Defining Constructor:


• Constructor name must be same as class name.
• Constructor does not have any return type not even void.
• Constructor must be defined under public section of the class.
• There can be more than one Constructor with different arguments.
• A Constructor should not have a return statement within the body of the Constructor.

Types of Constructors:
1. Default Constructor.
2. Parameterized Constructor.
3. Copy Constructor.

Page No: 1
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

4. Dynamic Constructor.
5. Explicit Constructor.

1. Default Constructor:
Constructor with no argument is called as Default Constructor.
There are two types of Default Constructor. They are
a) Compiler Defined Default Constructor:
❖ The Constructor which is provided by the compiler when the user has not defined any.
❖ It may not be physically synthesized by the compiler.
Example:
class exam
{
public:
exam ( )
{
}
};
b) User Defined Default Constructor.

❖ The Default Constructor synthesized by the compiler cannot do all the initializations that
we need for our class.
❖ Constructor without any argument is called Default Constructor.
❖ Inside the Constructor the value can be initialized according to the programmers need.
Example:
using namespace std;
#include<iostream>
class sum
{
int a, b;
public:
sum ( )
{
a = 10;
b = 20;
}
void display ( )
{
cout << “Sum= ” <<a+b;
}
};
void main ( )
{
sum s;
s.display( );
}

Output:
Sum= 30

Page No: 2
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

2. Parameterized Constructor:
• The Constructor that can take more arguments is called Parameterized Constructor.
• A Constructor can be overloaded by passing different number or different types of
arguments.
Syntax:
class classname
{
public:
class name (arguments)
{
-----
}
};
Example:
using namespace std;
#include<iostream>
class sum
{
int a, b;
public:
sum (int x, int y)
{
a = x;
b = y;
}
void display ( )
{
cout <<“Sum= ”<<a+b;
}
};
void main ( )
{
sum s(10,20);
s.display( );
}

Output:
Sum= 30

Overloaded Constructor: (or) Constructor Overloading.


Class having more than one constructor differentiated in the number of arguments or in
their types of arguments is known as Overloaded Constructor (or) Constructor Overloading.
Example:
using namespace std;
#include<iostream>
class sum
{
int a, b, c; float p, q, r;
public:
sum ( int x, int y)
{

Page No: 3
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

a = x; b = y;
c = a+b;
cout<<”Sum of 2 integer values =” <<c;
}
sum(float x, float y)
{
p = x; q = y;
r = p+q;
cout<<”Sum of 2 float values =” << r;
}
};
void main ( )
{
sum s1(10, 20);
sum s2(1.5, 2.8);
}

Output:
Sum of 2 integer values = 30
Sum of 2 float values = 4.3

3. Copy Constructor:
• The Constructor having reference to an instance of its own class as an argument is
known as Copy Constructor.
• The parameters of a Constructor can be of the data types except an object of its own class
as a value parameter.
• The process of initializing through Copy Constructor is known as Copy Initialization.
• When no Copy Constructor is defined, the compiler supplies its own Copy Constructor.
Syntax:
ClassName (ClassName &obj)
{
}

Program:
Example: 1
using namespace std;
#include<iostream>
class sum
{
int a, b;
public:
sum (int x, int y)
{
a = x;
b = y;
}
sum ( sum &obj)
{
a = obj.a;
b = obj.b;

Page No: 4
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

void display ( )
{
cout <<“Sum= ”<<a+b;
}
};
void main ( )
{
sum s1(10,20);
sum s2(s1);
s2.display( );
}
Output:
Sum= 30

Example: 2
using namespace std;
#include<iostream>
class book
{
public:
char *title;
int cost;
book (book &buk)
{
title = buk.title;
cost = buk.cost;
}
book(char *a, int c)
{
title = a;
cost = c;
}
void showbook( )
{
cout<<"Book Name: "<<title<<"Cost: "<<cost;
}
};
int main( )
{
book a ("OOPS",600);
book b (a);
book c = a;
book d;
d = a; //will not invoke copy constructor
a.showbook( );
cout<<"\nInvoking the copy constructor using Method 1: \n";

Page No: 5
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

b.showbook( );
cout<<"\nInvoking the copy constructor using Method 2: \n";
c.showbook( );
}

4. Dynamic Constructor:
• Allocation of memory to objects at the time of their construction is known as Dynamic
Construction of objects.
• The memory is allocated with the help of new operator.
• The Constructors can be used to allocate memory while creating objects. This will enable
the system to allocate the right amount of memory for each object when the objects are not
the same size, thus resulting in the saving of memory.
Program:
Example: 1
using namespace std;
#include<iostream>
class sum
{
public:
int *a, *b;
sum ( )
{
a = new int;
*a = 10;
b = new int;
*b = 20;
}
void display ( )
{
cout <<“Sum= ” << (*a+*b);
}
};
void main ( )
{
sum s1;
s1.display( );
}
Output:
Sum= 30

Example: 2 Program to join two strings


using namespace std;
#include<iostream>
class Example
{
public:
char *name; int length;
Example ( )
{

Page No: 6
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

length = 0;
name = new char [length +1];
}
Example (char *s)
{
length = strlen(s);
name = new char[length +1];
strcpy (name ,s);
}
void display ( )
{
cout <<name;
}
void join (Example &a, Example &b)
{
length = a.length + b.length;
delete name;
name = new char [length +1];
strcpy(name , a.name);
strcat (name, b.name);
}
};
void main ( )
{
Example name1(“EEE);
Example name2(“Department”);
Example s1;
s1.join(name1,name2);
name1.display ( );
name2.display ( );
s1.display ( );
}
Output:
EEE
Department
EEE Department

explicit Constructor:
• When we define a Constructor containing single argument, compiler automatically defines
a conversion operator for converting between the argument type and user defined object
type.
• The automatic conversion adds to readability and it is very useful.
• Sometimes the automatic conversion is not required. We can easily omit the creation of this
conversion operator by using the keyword explicit before the class name while defining the
object.
Syntax:

Page No: 7
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

explicit className (arguments)


{
}
Program:
using namespace std;
#include<iostream>
class flowers
{
string name;
public:
explicit flowers (string fnames)
{
name = fnames;
}
};
void main( )
{
flowers f1 = flowers (“rose”);
flowers f2 = “lotus” // error line
}

DESTRUCTOR:

• A Destructor is a function that automatically executes when an object is destroyed.


• A Destructor function gets executed whenever an instance of the class to which it belongs
goes out of scope.
• The use of the Destructor function is to release space on the heap.
• It can be invoked explicitly.
• Whenever new is used to allocate memory in the constructors, we should use delete to free
that memory. When delete gets executed then the destructor would be called.
Rules for Destructor:
• The Destructor name is same as that of the class name, except that the first character of
the name must be tilde (~) operator.
• It does not have return type.
• It does not take any argument. So it cannot be overloaded.
Syntax:
~ classname ( )
{
// body of the Destructor
}
Program:
using namespace std;
#include<iostream>
int count=0;
class Destruct

Page No: 8
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

{
public:
Destruct( )
{
count++;
cout<<"\nCreated object Number: "<<count;
}
~Destruct( )
{
cout<<"\nDestroyed object Number: "<<count;
count--;
}
};
main( )
{
cout<<"\nEntered inside main function\n";
Destruct d1, d2;
{
cout<<"\n\nEntered to Block No: 1\n";
Destruct d5;
}
{
cout<<"\n\nEntered to Block No: 2\n";
Destruct d6;
}
cout<<"\n\nRe-entered to main function\n";
}

Output:
Entered inside main function
Created object Number: 1
Created object Number: 2
Entered to Block No: 1
Created object Number: 3
Destroyed object Number:3
Entered to Block No: 2
Created object Number: 3
Destroyed object Number: 3
Re-entered to main function
Destroyed object Number: 2
Destroyed object Number: 1

The Destructor member function is invoked in the following situation:


• After the end of the main ( ) program.
• At the end of each block containing the auto variable of the class.
• At the end of each function containing an argument of class.
• When the instance of the class destroyed through delete operator.

Page No: 9
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

POLYMORPHISM:

• Polymorphism a Greek term means the ability to take more than one form.
• It allows a single name/operator to be associated with different operations depending on
the type of data passed on it.
• An operation may exhibit different behaviors in different instances. The behavior depends
upon the types of data used in the operation. For example consider the operation of
addition. For two numbers, the operation will generate a sum. If the operands are strings,
then the operation would produce a third string by concatenation.
• Polymorphism was classified into two types. They are,

Compile Time Polymorphism:


Invoking a function during compile time is called as Compile Time Polymorphism. It can
be implemented by two ways:
1. By Function Overloading
2. By Operator Overloading

(i) Function Overloading:

Function that shares the same name with different number of arguments or
different types of argument is called Function Overloading.

• It is used when we want to perform similar tasks but using different input parameters.
• When we call a function, C++ matches up the function name first and then the number and
type of parameter to decide which one of the definitions to execute.

Example Program:
using namespace std;
#include<iostream>
class overload
{
public:
int x, y, z, sum;
void add(int x, int y)
{
z=x+y;

Page No: 10
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

cout<<”sum=”<<z;
}
void add(int x, int y, int z)
{
sum=x+y+z;
cout<<”sum=”<<z;
}
};
void main( )
{
overload obj;
obj.add(2,8);
obj.add(1,2,5);
}

In the above program function named “add” was defined twice each time with different
number of arguments. First with 2 arguments and then with 3 arguments.

(ii) Operator Overloading:


• The mechanism of giving such special meaning to an operator is known as “Operator
Overloading”. C++ has the ability to provide the operators with a special meaning for a data
type.
• Operator overloading provides a flexible option for the creation of new definitions for most
of the C++ operators.
• The Operator is overloaded with the help of the special function called Operator function.
Syntax:
ReturnType operator Operator-to-be-overloaded (arguments);
Example:
void operator + ( ); Where operator is a Keyword.
• Operator function must be either normal member function or friend function.
The process of overloading involves the following steps:
1. Create a class that defines the data types that is to be used in the Overloading Operation.
2. Declare the Operator function in the public part of the class. It may be either a member
function or a friend function.
3. Define the Operator function to implement the required Operations.
Overloaded Operator functions can be invoked by the following expression:
a. For Unary Operator : Op X; (or) X op;
b. For Binary Operator : X op Y;
Where, Op - Operator name
X, Y – Object name
Rules for Overloading Operator:
1. Only existing operators can be overloaded. New operators cannot be created.

Page No: 11
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

2. The basic meaning of an operator cannot be changed.


3. The overloaded operator must have at least one operand that is of user-defined type.
4. Overloaded operators follow the syntax rules of the original operators.
5. There are some operators that cannot be overloaded.
6. We cannot use friend functions to overload certain operators.
7. Unary operators, overloaded by means of a member function, take no arguments but, those
overloaded by means of a friend function, take one reference argument (the object of the
relevant class).
8. Binary operators overloaded through a member function take one argument and those
which are overloaded through a friend function take two arguments.
9. While overloading binary operators the left hand operand must be an object of the relevant
class.
10. Binary arithmetic operators such as +, -, *, and / must explicitly return a value.
Operators that cannot be overloaded:
1. Scope resolution operator (::)
2. Size of operator (sizeof)
3. Conditional operator (?:)
4. Class member access operators (. , .*)
Operators that cannot be overloaded using friend function:
1. assignment operator =
2. function call operator ( )
3. subscripting operator [ ]
4. class member access operator ->
Example Program: ( Unary Operator )
using namespace std;
#include<iostream>
class Distance
{
int feet, inches;
public:
Distance( )
{
}
Distance(int x, int y)
{
feet=x; inches=y;
}
Distance operator ++ ( )
{

Page No: 12
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

feet++;
inches++;
if(inches>=12)
{
feet++;
inches=inches-12;
}
return Distance(feet, inches);
}
void display( )
{
cout<<"\nInches= "<<inches;
cout<<”\nFeet= “<<feet;
}
};
main( )
{
Distance d1(10,13);
Distance d2(2,7);
d1.display( );
d2.display( );
++d1; //invokes the operator overloaded function
++d2; //invokes the operator overloaded function
d1.display( );
d2.display( );
}

Output:
Inches= 12
Feet=2
Inches= 3
Feet=8

Example Program: ( Binary Operator )


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

Page No: 13
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

complex operator + (complex obj)


{
complex t;
t.a=a+obj.a;
t.b=b+obj.b;
return(t);
}
void display( )
{
cout<<a<<"+j"<<b<<"\n";
}
};
main( )
{
complex obj1(3,2), obj2(6,2), result;
result=obj1+obj2; //invokes the operator overloaded function
cout<<"Result: ";
result.display( );
}

Need For Using Friend Function:


Consider a situation where we need to use two different types of operator for a binary
Operator (i.e) one object and another built-in type data as shown below.
A = B + 2;
Where A & B are objects of the same class. This will work for a member function but the
statement,
A = 2 + B;
will not work. This is because the left-hand operand which is responsible for invoking the member
function should be an object of the same class. However friend function allows both approaches.
Overloading Through friend Function:
• Friend function may be used in the place of member functions for Overloading a binary
Operator.
• One difference being that a friend function requires two arguments, to be explicitly passed
to it, while a ordinary member function requires only one.
Example Program:
class complex
{
int a,b;
public:
complex( )
{
}
complex(int x, int y)
{
a=x; b=y;

Page No: 14
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

}
friend complex operator - (complex obj1, complex obj2)
{
complex t;
t.a=obj1.a-obj2.a;
t.b=obj1.b-obj2.b;
return(t);
}
void display( )
{
cout<<a<<"+"<<b<<"j"<<"\n";
}
};
void main( )
{
complex obj1(3,2),obj2(6,2),result;
result=obj1-obj2;
cout<<"Result: ";
result.display( );
}
In the above program the statement result=obj1-obj2; is equivalent to result = operator -
(obj1,obj2);

Overloading The Assignment Operator:


Commonly the Assignment Operator is used to assign a value / expression to a variable. But
overloading the assignment Operator may be required for the following situations.
1. When we have dynamic constructor and destructors.
2. When we convert one type of object into another, we can overload the assignment
Operator. If similar types of Objects are assigned to one another, they are copied bit by bit.
But it is not the same in case of different types of Objects.

Program:
class assign
{
public:
char name1[10], char name2[10];
assign( )
{
strcpy (name1, " " ); strcpy (name2, " " );
}
assign(char* s1,char* s2)
{
strcpy (name1,s1); strcpy (name2,s2);
}
assign operator = (assign a)
{
strcpy (name1, a.name1); strcat (name1, a.name2);
}
void display( )
{
cout<<"New String = "<<name1<<”\t”<<name2;
}

Page No: 15
21C S C 1 0 1T – O BJ EC T ORI E NT ED D ES IG N A N D P ROG RA M M IN G

};
main( )
{
char x[10], y[10];
cout<<”\nEnter two words:\n”;
cin>>x>>y;
assign a1(x, y), a2;
a2=a1; //invokes the overloaded function
a2.display( );
}

======================================================================

QUESTIONS:
1) What is Data Hiding? How it is implemented in C++. Explain it with an example.
2) Explain the concept of Friend Function with its characteristics.
3) Explain the different types of constructor with suitable C++ coding.
4) Explain copy constructor with suitable C++ coding.
5) Explain about Destructor in detail with proper example.
6) Explain the different types of polymorphism.
7) Explain about Function Overloading with an example to find greatest among two numbers.
8) State the rules to be followed while overloading an operator. Write a program to illustrate
operator overloading. (or) What is operator overloading? How many arguments are required
in the definition of an overloaded binary operator?
9) Briefly explain the types of operator overloading.
10) Write a program to overload unary operator ++ for incrementing distance. Assume that the
distance class has feet and inches as data members.
11) Explain about implementation of Run time polymorphism.
12) Write a C++ program using this pointer.

Page No: 16

You might also like