Unit 2 Notes
Unit 2 Notes
UNIT 2
METHODS AND POLYMORPHISM
=======================================================================
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”;
}
};
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
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
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
DESTRUCTOR:
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
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,
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.
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
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
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
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);
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