Oodp Unit 1
Oodp Unit 1
Oodp Unit 1
UNIT-1
Prepared by ,
CINTEL Team
8/24/2022 1
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING
Session 1
Eg : add(5,10);
8/24/2022 C ,C++ and UML Basics 5
Features of Procedure Oriented Programming
Language
• Smaller programs - A program in a procedural
language is a list of instructions.
• Larger programs are divided in to smaller programs
known as functions.
• Each function has a clearly defined purpose and a
clearly defined interface to the other functions in the
program.
• Data is Global and shared by almost all the functions.
• Employs Top Down approach in Program Design.
8/24/2022 C ,C++ and UML Basics 6
Examples of Procedure Oriented
Programming Language
• COBOL
• FORTRAN
•C
IDENTIFICATION DIVISION.
PROGRAM-ID.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 A PIC 9999.
77 B PIC 9999.
77 ANS PIC 999V99.
PROCEDURE DIVISION.
MAIN-PARA.
DISPLAY \”--------------------------------\”.
DISPLAY \” ENTER A\”
ACCEPT A. * command line argument
DISPLAY \”ENTER B\”.
ACCEPT B.
DISPLAY \”----------------------------------\”.
ADD-PARA.
ADD A B GIVING ANS.
DISPLAY \”-------------------------------------\”.
DISP-PARA.
DISPLAY \”A IS \” A.
DISPLAY \”B IS \” B.
DISPLAY \”ADDITION -\” ANS.
8/24/2022 STOP RUN. * to stopand
C ,C++ the UML
program
Basics 8
Disadvantages of Procedural
Programming Language
Unrestricted access
• functions have unrestricted access to global data.
Real-world modeling
• unrelated (separated) functions and data, the basis
of the procedural paradigm, provide a poor model
of the real world.
• Complex real-world objects have both attributes
(data) and behavior (function).
• The class is the repository for behavior associated with an object. That is, that
all objects that are instances of the same class can perform the same actions.
• Classes are organized into a singly rooted tree structure, called the inheritance
hierarchy.
• Memory and behavior associated with instances of a class are automatically
available to any class associatedC with
8/24/2022
a descendant in this tree structure.
,C++ and UML Basics 12
Object-Oriented Programming vs.
Procedural Programming
• Programs are made up of modules, which are parts of a program that can
be coded and tested separately, and then assembled to form a complete
program.
• This is where you start with a problem (procedure) and then systematically
break the problem down into sub problems (sub procedures).
8/24/2022 C ,C++ and UML Basics 13
Object-Oriented Programming vs.
Procedural Programming
Program is divided into small parts Program is divided into small parts
called ‘Functions’ called ‘Objects’
• For example
• cout<<“\n Enter the Marks”;
• cin>> ComputerNetworks>>OODP;
8/24/2022 C ,C++ and UML Basics 22
Reading and Writing Characters and Strings
• char marks;
• cin.get(marks);//The value for marks is read
• OR
• marks=cin.get();//A character is read and assigned to
marks
• string name;
• Cin>>name;
• string empname;
• cin.getline(empname,20);
• Cout<<“\n Welcome ,”<<empname;
Formatted I/O
A variable is the content of a memory location that stores a certain value. A variable is identified or denoted by a variable
name. The variable name is a sequence of one or more letters, digits or underscore, for example: character_
Rules for defining variable name:
❖ A variable name can have one or more letters or digits or underscore for example character_.
❖ White space, punctuation symbols or other characters are not permitted to denote variable name.
❖ A variable name must begin with a letter.
❖ Variable names cannot be keywords or any reserved words of the C++ programming language.
❖ Data C++ is a case-sensitive language. Variable names written in capital letters differ from variable names with the same
name but written in small letters.
In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this
1
problem by using scope resolution operator (::), because this operator allows access to the global version of
a variable. New Operator
2 The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new
operator initializes the memory and returns the address of the newly allocated and initialized memory to the
Delete Operator
pointer variable.
3 Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided
.
delete operator by C++ language Member Operator
4 C++ permits us to define a class containing various types of data & functions as members. To access a
member using a pointer in the object & a pointer to the member.
Void?
• When used in the declaration of a pointer, void specifies that the pointer is
"universal." If a pointer's type is void* , the pointer can point to any variable that's not
declared with the const or volatile keyword.
8/24/2022 41
Real Time Example
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary) Output: 101 Sonoo 890000
{
this->id = id; 102 Nakul 59000
this->name = name;
this->salary = salary;
}
void display() {
cout<<id<<" "<<name<<" "<<salary<<endl;
} };
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display(); e2.display(); return 0; }
8/24/2022 C ,C++ and UML Basics 46
Function using pointers
#include<iostream> void swap(int *a,int *b)
using namespace std; {
void swap(int *a ,int *b ); int c;
//Call By Reference c=*a;
int main() *a=*b;
{ *b=c;
int p,q; }
cout<<"\nEnter Two Number You Want To
Output:
Swap \n";
Enter Two Number You Want to
cin>>p>>q; Swap
swap(&p,&q); 10 20
cout<<"\nAfter Swapping Numbers Are Given After Swapping Numbers Are
below\n\n"; Given below
cout<<p<<" "<<q<<" \n"; 20 10
return 0;
} 8/24/2022 C ,C++ and UML Basics 47
MCQ
a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
8/24/2022 48
MCQ - Answer
a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a
8/24/2022 49
MCQ-What is output of the following code?
#include <iostream>
using namespace std;
int main()
{
char arr[20];
int i;
for(i = 0; i < 10; i++)
*(arr + i) = 65 + i;
*(arr + i) = '\0';
cout << arr;
return(0);
}
8/24/2022 50
MCQ - Answer
• Answer: ABCDEFGHIJ
Explanation: Each time we are assigning 65 +
i.
• In first iteration i = 0 and 65 is assigned.
• So it will print from A to J.
8/24/2022 51
Type conversion and type casting
• Type conversion or typecasting of variables refers to changing a variable of one
data type into another.
• While type conversion is done implicitly, casting has to be done explicitly by the
programmer.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// integer x
char y = 'a’;
// character y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
int z = x + 1;
cout << "x = " << x << endl<< "y = " << y << endl<< "z = " << z << endl;
8/24/2022 53
return 0;}
Type Casting
float sal=10000.00;
int income;
Income=int(sal);
8/24/2022 C ,C++ and UML Basics 54
Example for Explicit Type Conversion
#include <iostream>
using namespace std;
int main()
{ double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;}
Output:
Sum = 2
8/24/2022 55
Session-3
Class and objects - Features
class className
{
data members
member functions
};
8/24/2022 57
• Class is just a blue print, which declares and
Example
defines characteristics and behavior, namely class Room {
public:
data members and member functions
double length;
respectively. double breadth;
double height;
• All objects of this class will share these
characteristics and behavior. double calculateArea(){
return length * breadth;
• Class name must start with an uppercase
}
letter(Although this is not mandatory).
double calculateVolume(){
Example,
return length * breadth * height;
class Student }
};
8/24/2022 58
Define a Class Type
8/24/2022 59
- Data members Can be of any type, built-in or
user-defined.
This may be,
• non-static data member
Each class object has its own copy
Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined
l); width
int area(); r3 length
• The const member functions are the functions which are declared as constant in the program.
• The object called by these functions cannot be modified.
• It is recommended to use const keyword so that accidental changes to object are avoided.
• A const member function can be called by any type of object.
• Note: Non-const functions can be called by non-const objects only.
public :
void Write ( )
function definition
const ;
};
OBJECT
set of methods
Operations (member functions)
class Rectangle
main()
{ {
private: Rectangle r1;
Rectangle r2;
int width;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;
};
l); 5000
r1 r
int area(); width = 8
5 2
6000
length = 10
8 5000
???
};
#include <iostream.h>
• Only work for public data
members
class circle
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment
#include <iostream.h>
class circle
{
private:
double radius;
public:
void set (double r)
{radius = r;}
double get_r ()
{return radius;}
};
int main(void) {
circle c; // an object of circle class
c.set(5.0); // initialize an object with a public member function
cout << "The radius of circle c is " << c.get_r() << endl;
// access a private data member with an accessor
}
#include <iostream.h>
• Only work for public data
members
class circle
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment
class Rectangle
main()
{ {
private: Rectangle r1;
int width; Rectangle r2;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;
void set(int w, int l);
r2.set(8,10);
int area(); cout<<r2.area()<<endl;
}; }
8/24/2022 76
Example: 2
#include <iostream>
using namespace std;
// create a class
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
8/24/2022 77
Sample Exercises
1) Find whether the student is eligible for the current year placement from the
inputs student name, CGPA, gender (M/F), number of backlogs.
Implement the above by using object oriented programming concept.
3)Write a program that would print the information (name, year of joining,
salary, address) of three employees by creating a class named
'Employee'. The output should be as follows:
Name Year of joining Address
Robert 1994 64C- WallsStreat
Sam 2000 68D- WallsStreat
John 1999 26B- WallsStreat
8/24/2022 C ,C++ and UML Basics 78
Session-4
#include <iostream>
using std::cout; //this example “uses” only the necessary
using std::endl; // objects, not the entire std namespace
class Fraction {
public:
void assign (int, int); //member functions
double convert();
void invert();
void print();
private:
int num, den; //member data
};
Continued…
8/24/2022 C ,C++ and UML Basics 83
Using objects of a Class - Example
The main() function:
int main()
{
Fraction x;
x.assign (22, 7);
cout << "x = "; x.print();
cout << " = " << x.convert() << endl;
x.invert();
cout << "1/x = "; x.print(); cout << endl;
return 0;
}
Continued…
void main() {
Distance d1,d2;
d1.setFeet(2);
d1.setInches(2.2);
d2.setFeet(3);
d2.setInches(3.3);
d1.iFeet++; // ??????
cout<<d1.getFeet()<<d1.getInches()<<d2.getFeet()<<d2.getInche
s()<<endl;
8/24/2022 92
UML Diagrams - Introduction
8/24/2022 93
UML Diagrams - Introduction
SKETCH
•In this case, UML diagrams are only a lop-level view of the system
•It may not include all the necessary details to execute the project
•Forward Design:
•The design of the sketch is done before coding the application
•We can get a better view of the system or workflow that we are trying to create
•Many design issues or flaws can be revealed
•The overall project health and well-being can be improved
•Backward Design:
•After writing the code, the UML diagrams are drawn as a form of documentation
8/24/2022 94
UML Diagrams - Introduction
BLUEPRINT
•In this case, the UML diagram serves as a complete design that requires the
actual implementation of the system or software.
•Often, this is done by using CASE tools (Computer Aided Software Engineering
Tools)
•It needs more expertise and user training
8/24/2022 95
Overview of UML Diagrams
Behavioral
: behavioral features of a system / business process
Structural
: element of spec. irrespective of time • Activity
• State machine
• Class • Use case
• Component • Interaction
• Deployment
• Object
• Composite structure Interaction
• Package : emphasize object interaction
• Communication(collaberation
)
• Sequence
• Interaction overview
• Timing
8/24/2022 C ,C++ and UML Basics 96
Class Diagram
8/24/2022 97
Class Attributes
Person
SmokeAlarm
Responsibilities
8/24/2022 107
Class Diagram – cont..
Attributes : Second Section
• How would you identify each instance of
that class, i.e., a specific animal?
• Using Attributes
• What are Attributes?
• A significant piece of data containing values that describe each instance of that class
• They are also known as fields, variables or properties
• Format for specifying an attribute:
visibility attributeName : Type [multiplicity] = DefaultValue {property string}
• Visibility: It sets the accessibility of an attribute / method
• Private (-) Visible only to the elements within the same class
• Public (+) Visible to any element that can see the class
• Protected (#) Visible to the elements in the class and its sub class
• Package (~) Visible to elements within the same package
8/24/2022 108
Class Diagram – cont..
• Methods : Third section
• They are also known as operations or functions
• It specifies the behaviour of a class
• Eg: We may want to change the name of an Animal
• We could add a method setName
• We could also create a method for eating, since all of
our animals eat
• Lets take another example : Employee Details
8/24/2022 109
Multiplicity and Relationships
8/24/2022 110
Relationships
Association
• An association is a relationship between two separate
classes. It joins two entirely separate entities.
• There are four different types of association:
– Bi-directional
– Uni-directional
– Aggregation (includes composition aggregation)
– Reflexive.
• Bi-directional and uni-directional associations are the
most common ones.
• This can be specified using multiplicity (one to one, one
to many, many to many, etc.).
• A typical implementation in Java is through the use of
an instance field. The relationship can be bi-directional
with each class holding a reference to the other.
Inheritance
• Indicates that child (subclass) is considered to be a
specialized form of the parent (super class).
• For example consider the following:
Example
CourseSchedule
Course
add(c : Course)
remove(c :
Course)
Dependency - Aggregation
Student Employee
TeachingAssistant
Generalization Relationships
Multilevel Inheritance
(Cont’d)
Relationships b/w Classes
Inheritance (Generalization)
• Lets say in our zoo, the only animals we have are tortoises, otters and Slow Loris
• We make 3 new classes: Tortoise, Otter and
Slow Loris
• These subclasses inherit all the attributes and
methods of the superclass
• We could add an attribute specific to Otter
in the Otter class
• The main advantage of inheritance is that
if we wanted to change or add an attribute
for all animals, we need not make change in
every sub class
• We just make the change to the base class ‘Animal’ class and it applies across all sub classes
8/24/2022 121
Relationships b/w Classes
Abstraction
• In this example ‘Animal’ is the Abstract Class
• We will create instance for only the subclasses
• We wouldn’t instantiate the Animal class itself
• The Animal class is just a way to simplify things and keep the code “dry”
• To show that it is an Abstract class, we can write the name of the class in italics Animal or we
can enclose it like <<Animal>>
8/24/2022 122
Relationships b/w Classes
Association
• If we had a class for Sea Urchin
we could draw an association
• Sea otter is a marine mammal in
the north Pacific Ocean
• They eat mostly hard-shelled invertebrates
including sea urchins.
ASSOCI
ATION
8/24/2022 123
Aggregation ( (open diamond)
• It is a special type of association that specifies a whole and its parts, where a part can exist
outside the whose
• Lets take a group of tortoises, called creep
ASSOCIATION
A tortoise could leave the creep at any point and still
Exist on its own
8/24/2022 124
An aggregation specifies a whole-part relationship between an
aggregate (a whole) and a constituent part, where the part can
exist independently from the aggregate. Aggregations are
denoted by a hollow-diamond adornment on the association.
Engine
Car
Transmission
Composition
• It is a special type of association that specifies a whole and its parts, where the part cannot
exist outside the whole
• Example: Let us say we have several different visitors centers in our zoo. And each of those
visitor centers has a lobby and a bathroom
• Now if one of our visitors centers was torn down, the lobby and the bathroom of that visitor
center are torn down as well.
• Composition : A child object cannot exist without its parent object
8/24/2022 126
A composition indicates a strong ownership and coincident
lifetime of parts by the whole (i.e., they live and die as a
whole). Compositions are denoted by a filled-diamond
adornment on the association.
Scrollbar
1 1
Window Titlebar
1 1
Menu
1 1 .. *
Composition
• A restricted form of Aggregation in which two
entities (or you can say classes) are highly
dependent on each other.
• A human needs a heart to live and a heart needs a
human body to function on. In other words when
the classes (entities) are dependent on each other
and their life span are same (if one dies then
another one does too) then it’s a composition.
Multiplicity
• After specifying the type of association relationship by
connecting the classes, you can also declare the cardinality
between the associated entities. For example:
8/24/2022 132
Multiplicity Constraints
is registered for>
Student Semester
1..*
0..* 1
tak
g>
es>
rin
du
ld
he
0..8
1..*
is
teaches> Class
Instructor
Section
1..3 0..6
1..* is
in
st
a
<works for
nc
e
of
>
1 sponsors>
1 1..*
Department Course
Coming up: Multiplicity Constraints
Questions
• From the previous diagram
– How many classes can a student take?
– Do you have to be registered in any classes to be a
student?
– Do I need to teach this class to be an Instructor?
Do I need to teach ANY classes?
1. What type of core-relationship is represented by the symbol in the figure below?
a) Aggregation
b) Dependency
c) Generalization
d) Association
Answer: a
2. Which core element of UML is being shown in the figure?
a) Node
b) Interface
c) Class
d) Component
Answer: d
8/24/2022 135
3. What type of relationship is represented by Shape class and Square ?
a) Realization
b) Generalization
c) Aggregation
d) Dependency
Answer: b
8/24/2022 136
4. Consider a directed line (->) from the relation ship set advisor to both entity sets
instructor and student. This indicates ___________ cardinality.
a. One to many
b. One to one
c. Many to many
d. Many to one
Answer: b
5. An entity set that does not have sufficient attributes to form a primary key is
termed as a ____
a. Strong entity set
b. Variant set
c. Weak entity set
d. Variable set
Answer: c
8/24/2022 137
Association Relationships (Cont’d)
We can indicate the multiplicity of an association by adding
multiplicity adornments to the line denoting the association.
Student Instructor
1..*
Association Relationships (Cont’d)
The example indicates that every Instructor has one or more
Students:
Student Instructor
1..*
Association Relationships (Cont’d)
We can also indicate the behavior of an object in an association
(i.e., the role of an object) using rolenames.
membership
Student Team
1..* 1..*
Association Relationships
(Cont’d)
We can specify dual associations.
member of
1..* 1..*
Student Team
1 president of 1..*
Association Relationships
(Cont’d)
Associations can also be objects themselves, called link classes
or an association classes.
Registration
modelNumber
serialNumber
warrentyCode
Product Warranty
Association Relationships
(Cont’d)
A class can have a self association.
next
LinkedListNode
previous
Interfaces
An interface is a named set of
operations that specifies the behavior
<<interface>> of objects without showing their inner
ControlPanel structure. It can be rendered in the
model by a one- or two-compartment
rectangle, with the stereotype
<<interface>> above the interface
name.
A real world Example
8/24/2022 146
A Simple C++ Program with class
8/24/2022 147
Output
8/24/2022 148
18CSC202J - OBJECT ORIENTED
DESIGN AND PROGRAMMING
Session 8
Session - 11
• public •: A public member is accessible from anywhere outside the class but within a
program.
• private : A private member variable or function cannot be accessed, or even viewed from
outside the class. Only the class and friend functions can access private members.
167
• protected : A protected member variable or function is very similar to a private member
but it provided one additional benefit that they can be accessed in child classes which are
called derived classes
8/24/2022 C ,C++ and UML Basics
Syntax of Declaring Access Specifiers in C++
class ClassName
{
private:
// declare private members/methods here
public:
// declare public members/methods here
protected:
// declare protected members/methods here
};
168
#include <iostream>
int main()
using namespace std; {
class Sample // define a class Sample obj1; // declare a class object
{ cout << "Enter your age: ";
public: // public elements
int age; // store input in age of the obj1 object
cin >> obj1.age;
void displayAge()
{ obj1.displayAge(); // call class function
cout <<
•
"Age = " << age << endl; return 0;
} }
};
Output:
class Sample
{ int main()
private: // private elements {
int age; int ageInput;
Sample obj1;
public: // public elements cin >> obj1.age; // error
void displayAge(int a) cout << "Enter your age: ";
{ cin >> ageInput;
age = a; obj1.displayAge(ageInput);
•
cout << "Age = " << age << endl; return 0;
} }
};
Output:
};
Output:
1
7
4
•Even though the prototypes for friend functions appear in the class definition, friends are
not member functions.
176
//Global Function
#include <iostream>
void disp(XYZ obj)
using namespace std; {
class XYZ
cout<<obj.num<<endl;
{
cout<<obj.ch<<endl;
private: int num=100;
}
char ch='Z’; int main()
public: {
XYZ obj;
friend void disp(XYZ obj);
disp(obj);
}; return 0;
}
177
• When the inline function is called whole code of the inline function gets inserted or
substituted at the point of inline function call. This substitution is performed by the
C++ compiler at compile time.
include <iostream>
using namespace std;
inline int Max(int x, int y) { Output:
return (x > y)? x : y;
} Max (20,10): 20
// Main function for the program Max (0,200): 200
int main() { Max (100,1010): 1010
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
1. UML diagram that shows the interaction between users and system, is known as
A. Activity diagram
B. E-R diagram
C. Use case diagram
D. Class diagram
Answer:C
• Constructor get automatically invoked when instance or object for the class is created
• When a class is instantiated, even if we don’t declare a constructor, compiler automatically creates
one for the program. This compiler created constructor is called default constructor.
• The name of the constructor must be the same as the name of the class.
•8/24/2022
A Class can have any number of constructor provided properly overloaded. 199
Features of Constructor
• It doesn't have any return type, not even void. Hence, it can't return values.
• It can't be inherited, though a derived class can call the base class constructor.
• Constructors should always be non-virtual. They are static functions and in C++ so they cannot be
virtual.
•8/24/2022
A class can have more than one constructor i.e. constructors can be overloaded. 200
Syntax for Constructor: Example:
class classname class Student
{ {
public: int rno;
classname([parameter_list]) public:
{ Student(int no)
//constructor definition {
} rno = no;
}; }
};
8/24/2022 201
Types of Constructor
Types of Constructors in C++
Constructors are of three types:
• Default Constructor - Default constructor is the constructor which
doesn't take any argument. It has no parameter.
• Parametrized Constructor : These are the constructors with
parameter. Using this Constructor you can provide different values to
data members of different objects, by passing the appropriate values as
argument.
• Copy Constructor: These are special type of Constructors which
takes an object as argument, and is used to copy values of data
members of one object into other object.
8/24/2022 C ,C++ and UML Basics 202
Default Constructor:
• In this case, default constructor provided by the compiler will be called which will initialize the
Example:
int main()
object data members
class Bank_Account to default value, that will be 0 or any random integer value in this case.
{
{ Bank_Account b1;
int accno,balance; return 0;
public: }
Bank_Account()
{
accno =9999;
balance=1000;
}
};
8/24/2022 203
Parameterized Constructor:
The Constructors that can take arguments are called parameterized constructor. Sometimes, it may be
necessary to initialize the data members of different objects with different values when they are
created.
Example:
int main()
class Bank_Account {
{ Bank_Account b1(101,10000);
int accno,balance; return 0;
public: }
Bank_Account(int a, int b)
{
accno =a;
balance=b;
}
};
8/24/2022 204
Example for constructor with parameter
Creating an
#include <iostream> object of
using namespace std; Employee
class Employee {
int main(void) {
public:
int id;//data member (also
Employee e1 =Employee(101, "Sonoo",
instance variable) 890000); e2=Employee(102, "Nakul", 59000);
string name;//data member(also e1.display();
instance variable) e2.display();
float salary; return 0;
Employee(int i, string n, float s) }
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<"
"<<salary<<endl;
}
};
Copy constructor is used for creating a new object as a copy of an existing object. It si used when we
need to coy data members from one object to another object. It takes reference to an object of the
same class as an argument.
• Whenever objects are constructed based on another object that is of the same class.
8/24/2022 206
Copy Constructor
8/24/2022 207
Example for copy constructor
8/24/2022 209
Destructor
• Destructor is a special class function which destroys the object as soon as the scope of object ends.
The destructor is called automatically by the compiler when the object goes out of scope.
• The syntax for destructor is same as that for the constructor, the class name is used for the name of
Syntax:
class classname
public ~classname()
{}
};
8/24/2022 210
When does the destructor get called?
• Destructors cannot be overloaded i.e., there can be only one destructor in a class
8/24/2022 213
Example: Student( Student &s1)
{
#include <iostream> rollno= s1.rollno; name=s1.name;
using namespace std;
class Student }
{ void display()
public: {
int rollno; cout<<this->rollno<<" "<<this->name<<endl;
string name; //default }
Constructor //destrcutor
Student() ~Student()
{ {
rollno=-1; name=""; cout<<"destructor invoked"<<endl;
}
} };
// parametrized constructor Student(int int main() {
x, string str) { Student s;
rollno = x; name = str; Student s1(101,"Abinav");
} Student s2(s1);
s.display();
s2.display();
return 0;
8/24/2022 214
}
Methods
• A method is a function that is part of the class definition. The methods of a
class specify how its objects will respond to any particular message.