Unit 2
Unit 2
Unit 2
Unit II
Types of Constructor
1/26/2023 Constructor's 2
Agenda :
1) To understand types of Constructor’s.
2) To apply Constructor’s in real time example.
1/26/2023 Constructor's 3
CONSTRUCTORS
• It is very common for some part of an object to require
initialization before it can be used.
• They do not have return types, not even void and they cannot
return values.
• Example
• Output : 10
DEFAULT CONSTRUCTOR
• As soon as the object is created the constructor is called which initializes its
data members.
OUTPUT
10
20
30
PARAMETERIZED CONSTRUCTOR
• As it is used to create an object, hence it is called a constructor. And, it creates a new object,
which is exact copy of the existing copy, hence it is called copy constructor.
COPY CONSTRUCTOR
COPY CONSTRUCTOR
Output :
Normal constructor : 10 15
Copy constructor : 10 15
STATIC CONSTRUCTOR
• C++ doesn’t have static constructors but you can emulate them using a static instance of a nested
class.
class has_static_constructor {
friend class constructor;
struct constructor {
constructor() { /* do some constructing here … */ }
};
static constructor cons;
};
1/26/2023 Constructor's 23
Questions
1. What is a copy constructor?
a) A constructor that allows a user to move data from one object to another
b) A constructor to initialize an object with the values of another object
c) A constructor to check the whether to objects are equal or not
d) A constructor to kill other copies of a given object.
2. What happens if a user forgets to define a constructor inside a class?
a) Error occurs
b) Segmentation fault
c) Objects are not created properly
d) Compiler provides a default constructor to avoid faults/errors.
3. How many parameters does a copy constructor require?
a) 1
b) 2
c) 0
d) 3
1/26/2023 Constructor's 24
Unit 2-
Polymorphism -
OVERLOADING
Introduction
30
Operator Overloading
• Examples of already overloaded operators
• Operator << is both the stream-insertion operator and the
bitwise left-shift operator
• + and -, perform arithmetic on multiple types
• Compiler generates the appropriate code based on the
manner in which the operator is used
General Rules for Operator Overloading
• Overloading an operator - Write function definition as normal
Syntax:
returnType classname::operator op(arguments)
{
Function body;
} Function name is keyword operator followed by the symbol for the
operator being overloaded
32
General Rules for Operator Overloading
• Using operators
• To use an operator on a class object it must be overloaded
unless the assignment operator(=)or the address
operator(&)
• Assignment operator by default performs memberwise
assignment
• Address operator (&) by default returns the address of
an object
Steps
1. Create a class that is to be used
2.Declare the operator function in the public part of the class. It may be
either member function or friend function.
3.Define operator function to implement the operation required
4.Overloaded can be invoked using the syntax such as: op x;
Restrictions on Operator Overloading
35
Restrictions on Operator Overloading
• Overloading restrictions
• Precedence ,associativity, arity (number of operands) of
an operator cannot be changed
• No new operators can be created
• Use only existing operators
• No overloading operators for built-in types
• Cannot change how two integers are added
36
Overloadable Operators
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
Non-overloadable Operators
:: .* . ?:
Approaches
• Operator Overloading can be done by using three approaches, they
are
• The difference between the copy constructor and the assignment operator causes a lot of confusion
for new programmers, but it’s really not all that difficult. Summarizing:
• If a new object has to be created before the copying can occur, the copy constructor is used (note: this
includes passing or returning objects by value).
• If a new object does not have to be created before the copying can occur, the assignment operator is
used.
#include <iostream>
using namespace std;
class Distance {
private: int feet; // 0 to infinite
int inches; // 0 to 12
public: // required constructors
Distance() { feet = 0; inches = 0; }
Distance(int f, int i)
{ feet = f; inches = i; }
void operator = (const Distance &D )
{ feet = D.feet; inches = D.inches; }
// method to display distance
void displayDistance() { cout << "F: " << feet << " I:“ << inches << endl;
} };
int main()
{ Distance D1(11, 10), D2(5, 11);
cout << "First Distance : "; D1.displayDistance();
cout << "Second Distance :"; D2.displayDistance();
// use assignment operator
D1 = D2; cout << "First Distance :";
D1.displayDistance(); return 0; }
Output:
First Distance : F: 11 I:10 Second Distance :F: 5 I:11 First Distance :F: 5 I:11
// CPP program to illustrate
Binary Operator Overloading
// Operator Overloading
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Operator Overloading MCQ
1) Which is the correct example of a unary operator?
a) &
b) ==
c) —
d) /
2) What is a binary operator give example?
a) Operator that performs its action on a single operand, ++
b) Operator that performs its action on two operand , --
c) Operator that performs its action on three operand , Dereferencing
operator(*)
d) Operator that performs its action on any number of operands , +
Given the following C++ code. How would you define the < operator for Box class so that
when boxes b1 and b2 are compared in if block the program gives correct result?
#include <iostream>
#include <string>
using namespace std;
class Box {
int capacity;
public: Box(){}
Box(double capacity){
this->capacity = capacity; } };
int main(int argc, char const *argv[]) {
Box b1(10);
Box b2 = Box(14);
if(b1 < b2){
cout<<"Box 2 has large capacity.";
} else{
cout<<"Box 1 has large capacity.";
} return 0; }
Answers:
a) bool operator<(Box b) { return this->capacity < b.capacity ? true : false; }
b) bool operator<(Box b) { return this->capacity > b.capacity ? true : false; }
c) bool operator<(Box b) { return b1 > b2 ? true : false; }
d) bool operator<(Box b) { return this < b ? true : false; }
Function Overloading
Agenda :
1) To understand about method overloading
2) To apply method overloading in real time example.
• Is the process of using the same name for two or more functions
• Requires each redefinition of a function to use a different function
signature that is:
• different types of parameters,
• or sequence of parameters,
• or number of parameters
• Is used so that a programmer does not have to remember multiple
function names
Method Overloading
• Method overloading is a feature in C++ that allows creation of
several methods with the same name but with different
parameters.
void area(int x)
{ cout<<“area is”<<x*x;
}
void area(int x,int y)
{cout<<“area of rectang;e”=<<x*y;
}
void area(int x,int y,int z)
{cout<<“volume is”<<x*y*z;
}
int main(){
int side=10,le=5,br=6,a=4,b=5,c=6;
area(side);
area(le,br);
area(a,b,c);
return 0;}
Function Selection Involves following Steps.
• Compiler first tries to find the Exact match in which the type of
argument are the same,and uses that func.
• If an exact match is not found,the compiler user the integral
promotions to the actual argument such as,char to int, float to
double.
• When either of them fails ,build in conversions are used(implicit
conversion) to the actual arguments and then uses the function
whose match is unique. But if there are multiple matches, then
compiler will generate an error message.
• For ex: long square(long n)
long square(double x)
1. There are multiple definitions for the same function name in the same scope
2. The definitions of these functions vary according to the types and/or the number of
arguments in the argument list
3. Data type of the return value is not considered while writing overloaded functions because
the appropriate function is called at the compile time while the return value will be
obtained only when the function is called and executed
Try out Program
CONTD...,
obj1.getdata(10,20,30);
obj1.display();
-obj1;
obj1.display();
return 0;
}
Output:
x=10
y=20
z=30
x=-10
y=-20
z=-30
INTRODUCTION
In Binary operator overloading function, there should be one
argument to be passed.
It is overloading of an operator operating on two operands.
#include<iostream>
class multiply
{
int first,second;
public:
void getdata(int a,int b)
{
first=a;
second=b;
}
Contd...,
void display()
{
cout<<“first=“<<first<<“second=“<<secon<<endl;
}
multiply operator *(multiply c);
};
void multiply::operator *(multiply c)
{
multiply temp;
temp.first=first*c.first;
temp.second=second*c.second;
return temp;
}
Contd..,
int main()
{
multiply obj1,obj2,obj3;
obj1.getdata(15,20);
obj2.getdata(3,45);
obj3=obj1*obj2;
obj3.display();
return 0;
}
Output:
45
900
18CSC202J- Object Oriented
Design and Programming
Unit II
• Sequence diagram
• Collaboration diagram.
➢We represent messages using arrows. Lifelines and messages form the core of a sequence
diagram.
▪ An asynchronous message does not wait for a reply from the receiver.
▪ The interaction moves forward irrespective of the receiver processing the
previous message or not.
▪ We use a lined arrow head to represent an asynchronous message.
• Reply messages are used to show the message being sent from the receiver
to the sender.
• The interaction moves forward only when a reply message is sent by the
receiver.