Defining class
Defining member functions
Static data members
Static member functions
Private data members
Public member functions
Arrays of objects
Objects as a function arguments
Constructors and destructors
Types of constructors
Handling of multiple constructors, destructors.
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
OOP Unit 2 - Classes and Object
1. CLASSES AND
OBJECTS
By- Ms. Dipali K. Pawar
ME(Comp), BE(Comp)
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
Unit II
2. Contents
• Defining class
• Defining member functions
• Static data members
• Static member functions
• Private data members
• Public member functions
• Arrays of objects
• Objects as a function arguments
• Constructors and destructors
• Types of constructors
• Handling of multiple constructors, destructors.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
3. Structure overview
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A structure is collection of simple variable, the variable in a structure can be of different
type.
• Ex:
struct student
{
int roll_no;
char name[20];
float marks;
};
• The keyword struct declares student as new data type that can hold three fields of
different datatypes. These fields are known as structure members or elements.
• The identifier student, which is referred to as structure name or structure tag, can be used
to create variables of type student.
4. Structure overview
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Ex. struct student A;
A is a variable of type student and has three member variables as defined by the
template.
Member variables can be accessed using dot or period operator as follows:
strcpy(A.name, “John”);
A.roll_number = 999;
A.total_marks = 595.5;
Final_total = A.total_marks+5;
Structures can have arrays, pointers or structures as members.
5. Structure overview
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Limitations of C structure:
It doesn’t allow the struct datatype to be treated like built-in types.
Ex.
struct complex
{
float x;
float y;
};
struct complex c1, c2, c3;
The complex numbers c1, c2 and c3 can easily be assigned values using dot operator, but we cannot
add two complex numbers or subtract one from the other.
Ex. c3=c1+c2; is illegal in C
They don’t permit data hiding, i.e. they can be accessed directly by structure variables by any function
anywhere in the program.
Structure members are public members.
6. Why classes?
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
C++ supports all the features of structure defined in C, but C++ has expanded its capability further to suit its
OOP philosophy.
In C++ structure can have both variables and functions as members. It can also declare some of its members
as private so that they can be accessed directly by external functions.
C++ incorporates all these functionalities and extensions of structures in a new user-defined data type called
“class”.
7. Defining Class
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A class is a way to bind data and associated function together.
• A class is an expanded concept of a data structure, instead of holding only data , it
can hold both data and function.
• The data is to be hidden from external use.
• When defining a class, we are creating a new abstract data type that can be treated like
any other built-in data type.
• Generally, a class specification has two parts:
1. Class Declaration
2. Class functions definitions
Class Declaration describes the type and scope of its members.
Class function definitions describe how the class functions are implemented.
8. Defining Class
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Classes are generally declared using the keyword class, with the following
format:
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
9. • The body of the declaration can contain members that can be either data or function
declaration, and optionally access specifier.
• The variable declared inside the class is known as data member and function are known as
member functions.
• Access specifier are keyword in object oriented language that set the accessibility of classes,
method and other member.
• Access specifier is one of the following keyword: public, private, protected.
Note that these keywords are followed by a colon.
• These specifier modify the access rights that the member following them acquire:
private members of class are accessible only from within other member of same class or
from their friends.
protected members are accessible form members of their same class and from their friends
but also from members of their derived classes.
public members are accessible from anywhere the object is visible.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
10. • A Simple class example:
class item
{
int number; // variables declaration
float cost; //private by default
public:
void getdata(int a, float b); //functions declaration
void putdata(void);
}; //using prototype ends with semicolon
• By default, all members of class declared with the class keyword have private access for all its
member. Therefore, any member that is declared before one other class specifier automatically
has private access.
• Only member function can have access to private data member and private function of that
data.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
11. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Structure Class
1. By default the members of structure are public. 1. By default the members of class are private.
2. The structure cannot be inherited. 2. The class can be inherited.
3. The structures do not require constructors. 3. The classes require constructors for initializing the
objects.
4. A structure contains only data members. 4. A class contains the data as well as the function
members.
5. Structs are of value types. 5. Classes are of reference types.
6. All the value types are allocated on stack memory. 6. All the reference types are allocated on heap
memory.
7. Struct has limited features. 7. Class has limitless features.
8. Struct are used in small programs. 8. Class is generally used in large programs.
9. Structure does not contain parameter less
constructor or destructor, but can contain
Parameterized constructor or static constructor.
9. Classes can contain constructor or destructor.
10. The data member of struct can’t be protected. 10. The data member of a class can be protected.
12. Creating Objects
• Once a class has been created, we can create variable of that type(class
type) by using following syntax which is called object.
• Syntax:
class_name variable_name;
Ex:
student s;
• We can create any number of objects belonging to that class by
declaring more than one object in one statement. This statement are
written in main().
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
13. Creating Objects
• The objects can also be defined by placing their name immediately after
the closing brace of the class.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Syntax:
class class_name
{
….
}object1,object2,…;
• Ex:
class student
{
…
}s1,s2;
14. Accessing Class Members
• A object can be declared in the main(),and member functions are declared in class in
public section so always a member function can be called by using object.
• Syntax:
object_name.member_function(arguments);
Ex:
s.getdata();
• A data member can also be access by using object only , if data member is declared as
public.
• If data member is declared private then you can not access it by using object directly in
object.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
15. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Class Object
1. Class is a blueprint or template from which objects
are created.
1. Object is an instance of a class.
2. Class is a logical entity. 2. Object is a physical entity.
3. A class does not allocate memory space when it is
created.
3. Object allocates memory space whenever they are
created.
4. You can declare class only once. 4. You can create more than one object using a class.
5. Class is declared using class keyword -
class classname{ };
e.g. class Student{};
5. Object is created as classname objectname;
e.g. Student s1;
6. A class is used to bind data as well as methods
together as a single unit.
6. Object acts like a variable of the class.
7. Class: Fruit 7. Object: Apple, Banana, Mango, Guava wtc.
16. Defining Class
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A member function can be defined in two places in the class:
1. inside the class definition
2. outside the class definition
17. 1. Inside the class definition:
To write a member function inside the class instead of only declaration(prototype).
Ex:
class item
{
int num;
float cost;
public:
void getdata(int a,float b); //function declaration
void putdata(void) // function definition
{
cout<<number; cout<<cost;
}
};
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
18. 2. Outside the class definition:
• To write function we need to declare function inside the class and definition(function body)
is written outside the class.
• The general form of a member function definition:
return_type class_name :: function_name(argument)
{
function body
}
• The membership label class_name :: tells the compiler that the function function_Name
belongs to the class class_name.
• :: is scope resolution operator.
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
19. Ex: class item
{
int number, cost;
public:
void getdata(int a,int b);
void putdata();
};
void item::getdata(int a, float b)
{
number=a;
cost=b;
}
void item::putdata(void)
{
cout<<“number“<<number<<“n”;
cout<< “cost ”<<cost<<“n”;
}
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
20. Making outside function inline
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• We can define a member function outside and still make it inline by just using the qualifier
inline in the header line of function definition.
• Ex:
class item
{
public:
void getdata(int a,float b); //function declaration
};
inline void item :: getdata(int a,float b) //function defintion
{
number = a;
cost = b;
}
21. Nesting member functions
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A member function can be called by using its name inside another member
function the same class is called nesting member function.
22. Ex:
#include<iostream>
using namespace std;
class number
{
private:
int a,b,s1,s2;
public:
int getdata(int m,int n);
int sum();
int sub();
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
int show()
{
cout<<"n Enter number1: ";
cin>>a;
cout<<"n Enter number2: ";
cin>>b;
cout<<"n Answer of Addition:"<<sum()<<endl;
cout<<"n Answer of
substraction:"<<sub()<<endl;
}
};
int number::getdata(int m,int n)
{
a=m;
b=n;
}
int number::sum()
{
s1=a+b;
return(s1);
}
int number :: sub()
{
s2=a-b;
return(s2);
}
int main()
{
number x;
x.getdata(10,20);
x.show();
return 0;
}
23. Private member functions
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Generally we declare , data members are in private section and member function in
public section, that’s why we call a member function from main() through object.
• But if we declare a member function in private section then we can not call directly
from the main(), because it’s private function.
• To call private function , we have to create public function of that class and we call
this private function inside that public function , then the public function called by
object from main().
24. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Ex:
#include<iostream>
using namespace std;
class value
{
private:
int a,b;
void getdata();
public:
void show();
};
void value::getdata()
{
cout<<"Enter number1: ";
cin>>a;
cout<<"Enter number2: ";
cin>>b;
}
void value::show()
{
getdata();
cout<<"Two numbers are "<<a <<"n"<<b;
}
int main()
{
value v;
v.show();
return 0;
}
25. Memory allocation for objects
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The memory space for objects are allocated when they are declared, not when the class
is specified.
• For member function, when member function are created, it will occupy the memory
space only once when they are defining in a class.
• So all objects created for that class can use same member functions, so no separate
space is allocated for member functions when the object are created.
• For data member, only space for data members is allocated separately for each object
when is created.
• The separate space allocation for data member is essential because the data member
will hold different data values for different objects.
26. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• For example, a class student have
• three data members such as name, age, address
• two member functions getdata() and show()
• If we create three object S1 ,S2, S3 then,
• object S1 takes up space for: name, age, address
• object S2 takes up space for: name, age, address
• object S3 takes up space for: name, age, address
• But it will access common member function getdata() and show(), so it will take up space only one time
when class is created.
27. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Common for all objects
member function 1
member function 2 Memory is created when
functions defined
object 1
member variable 1
member variable 2
object 2
member variable 1
member variable 2
object 3
member variable 1
member variable 2
Memory is created when
objects defined
Fig. 2.1 Object of memory
28. Static Data Members
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Static variable are normally used to maintain values common to the entire class.
• For example, a static data member can be used as a counter that record occurrences of
all the objects.
• A static member variable has certain characteristic:
1. It automatically initialized zero when the first object is created , no other
initialization is permitted. Where a simple variable have initially garbage value.
2. Only one copy of that member is created for entire class and shared by all objects
of that class, no matter how many objects are created.
3. It is visible only within a class, but its life time is the entire program.
29. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Ex:
#include<iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number =a;
count++;
}
void getcount(void)
{
cout<<“count:”;
cout<<count<<“n”;
}
};
int item:: count; //definition of static data member
int main()
{
item a, b, c;
a.getcount(); //count is initialized to zero
b.getcount(); //display count
c.getcount();
a.getdata(100); //getting data into object a
b.getdata(200); //getting data into object b
c.getdata(300); //getting data into object c
cout<<“After reading data”<<“n”;
a.getcount(); //display count
b.getcount();
c.getcount();
return 0;
}
Output:
count: 0
count: 0
count: 0
After reading data
count: 3
count: 3
count: 3
30. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The type and scope of each static member variable must be defined outside the class definition.
• This is necessary because the static data members are stored separately rather than as a part of an object.
• Since they are associated with class itself rather than with any class object, they are also known as class
variable.
• The static variable count is initialized to zero when the objects are created.
• The count is incremented whenever data is read into an object.
• Since the data read into objects three times, the variable count is incremented three times.
• Because there is only one copy of count shared by all the three objects, all the three output statements
cause the 3 to be displayed.
31. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
100
Object 1
number
200
Object 2
number
300
Object 3
number
3
count
(common to all three objects)
Fig. 2.2 Sharing of a static data member
32. Static Member Functions
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A member function that is declared static has the following
properties:
A static function can have access to only other static
members(function or variable) declared in the same class.
A static member function can be called using the class name.
like,
class_name :: Function_name();
Ex. test :: getdata();
33. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Ex:
#include<iostream>
using namespace std;
class test
{
int code;
static int count; //static member variable
public:
void setcode(void)
{
code = ++count;
}
void showcode(void)
{
cout<<“object number:”<<code<<“n”;
}
static void showcount(void)
{
cout<<“count:”<<count<<“n”;
}
};
int item:: count; //definition of static data member
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test:: showcount();
test t3;
t3.setcode();
test:: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0;
}
Output:
count: 2
count: 3
object number: 1
object number: 2
object number: 3
34. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The static function showcount() displays the number of objects created till the moment.
• A count of number of objects created is maintained by the static variable count.
• The function showcode() displays the code number of each object.
• Note that the statement
• code = ++count;
• is executed whenever setcode() function is invoked and the current value of count is assigned to code.
• Since each object has its own copy of code, the value contained in code represents a unique number
of its object.
35. Arrays of Objects
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• As an array can be of any data type including struct. Similarly, we can also have arrays
of variable that are of the type class. Such variables are called array of objects.
• For example:
class employee
{
char name[30];
float age;
public:
void getdata(void);
void putdata(void);
};
For this class if we required 100 employee, then we are not declare different s1,s2,…,s100 object
because it’s very critical task. For this problem we use array of object.
36. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The identifier employee is a user-defined data type and can be used to create objects that relate to
different categories of the employees.
• Ex. employee manager[3]; //array of manager
employee foreman[15]; //array of foreman
employee worker[75]; //array of worker
The array manager contains three objects(managers), namely, manager[0], manager[1] and manager[2],
of type employee class.
Similarly, the foreman array contains 15 objects(foreman) and the worker array contains 75
objects(workers).
• An array of objects behaves like any other array, we can use the usual array-accessing methods to access
individual elements, and then dot operator to access the member functions.
Ex. manager[i].putdata();
will display the data of ith element of the array manager.
i.e., this statement requests the object manager[i] to invoke the member function putdata().
37. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• An array of objects is stored inside the memory in the same way as a multi-dimensional array.
• The array manager is represented in fig. 2.3
• In this fig. only the spaces for data items of the objects is created.
• Member function are stored separately and will be used by all the objects.
name
name
name
age
age
age
manager[0]
manager[1]
manager[2]
Fig 2.3 Storage of data items of an array
39. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Interactive input
Details of manager1
Enter name: xxx
Enter age:45
Details of manager2
Enter name: yyy
Enter age:37
Details of manager3
Enter name: zzz
Enter age:50
Program input
Manager1
Name: xxx
Age:45
Manager2
Name: yyy
Age:37
Manager3
Name: zzz
Age:50
40. Objects as Function Arguments
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Like any other data type, an object may be used as a function
argument. This can be done in two way:
1. A copy of the entire object is passed to the function, which is called call/pass
by value.
2. Only the address of the object is transferred to the function, which is called
call/pass by reference.
• This means that any changes made to the object inside the function will
reflect in the actual object.
• The pass by reference method is more efficient since it requires to pass only
the address of the object and not the entire object.
41. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
using namespace std;
class time
{
int hours;
int minutes;
public:
void gettime(int h, int m)
{
hours =h;
minutes =m;
}
void puttime(void)
{
cout << hours<<“hours and”;
cout<<minutes<<“minutes”<<“n”;
}
void sum(time, time ); //declarations with objects are arguments
};
void time :: sum(time t1, time t2) //t1, t2 are objects
{
minutes=t1.minutes+ t2.minutes;
hours = minutes/60;
minutes = minutes%60;
hours = hours+t1.hours+t2.hours;
}
int main()
{
time T1,T2,T3;
T1.gettime(2,45); //get T1
T2.gettime(3,30); //get T2
T3.sum(T1,T2); //T3=T1+T2
cout<<“T1 =”;
T1.puttime();
cout<<“T2 =”;
T2.puttime();
cout<<“T3 =”;
T3.puttime();
return 0;
}
Output:
T1 = 2 hours and 45 minutes
T2 = 3 hours and 30 minutes
T3 = 6 hours and 15 minutes
42. Friendly functions
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Due to ‘data hiding ’ feature of c++, the private data members of class can not be
access outside the class. So a function which are not member of the class, they can not
be access the private data of that class.
• In c++, there is facility available to access private data of class even if it is not member
function of that class. It is possible by using friend function.
• As the name suggests, the function acts as a friend to a class. As a friend of a class, it
can access its private and protected members.
• To make an outside function “friendly” to class, declare the function as friend of that
class.
43. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The friend functions are declared by using friend keyword.
• Syntax:
friend return_type function_name(arg_list);
• Generally arguments in friend functions are object type. Because of outside the class a data
member can not directly access, so a object can access it.
• A function can be declared as friend for any number of class. It can not be member function of
any class. It have full rights to access private data of the class.
44. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Advantage of having friend function:
1. We can able to access the other class members in our class, if we use friend keyword.
2. We can access the members without inheriting the class.
• Disadvantage:
1. Maximum size of memory will occupied by object according to the size of
friend member.
2. Break the concept of ‘data hiding’ in oop.
45. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Characteristic of friend function:
1. It is not in the scope of the class which it has been declared as friend.
2. It can not be called using the object of that class. It can be invoked like a normal function
without the help of object.
3. It can not access data member directly, it must be use object with dot(.) operator and data
member.
4. Normally it has object as argument.
46. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
using namespace std;
class MEAN
{
int n1,n2;
public:
void getdata()
{
cout<<"Enter num1: ";
cin>>n1;
cout<<"Enter num2: ";
cin>>n2;
}
friend float ans(MEAN m);
};
float ans(MEAN m)
{
return float(m.n1+m.n2)/2;
}
int main()
{
MEAN m1;
m1.getdata();
cout<<"Answer is: "<<ans(m1);
return 0;
}
Output:
Enter num1: 5
Enter num2: 10
Answer is: 7.5
47. Constructors
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A constructor is a special member function whose task is to initialize the data
members of an objects of its class.
• It is special because it has same name as its class name.
• It invokes automatically whenever a new object of its associated class is created.
• It is called constructor because it constructs the initial values of data members of the
class and build your programmatic object.
48. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• It is very common for some part of an object to require initialization before it can be used.
• Suppose you are working on 100's of objects and the default value of a particular data member is
needed to be zero.
• Initializing all objects manually will be very tedious job.
• Instead, you can define a constructor function which initializes that data member to zero. Then
all you have to do is declare object and constructor will initialize object automatically.
49. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
A constructor is declared and defined as follows:
//class with a constructor
class integer
{
int m,n:
public:
integer(void); //constructor declared
};
integer :: integer(void) //constructor defined
{
m=0;
n=0;
}
• When a class contains a constructor like the one defined
above it is guaranteed that an object created by the class
will be initialized automatically.
• For example, the declaration
integer int1; //object int1 created
• This declaration not only creates the object int1 of type
integer but also initializes its data members m and n to
zero.
50. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Characteristics of Constructor:
• They must be declared in the public scope.
• They are invoked automatically when the objects are created.
• They do not have return types, not even void and they cannot return values.
• They cannot be inherited, though a derived class can call the base class constructor.
• Like other C++ functions, Constructors can have default arguments.
• Constructors can not be virtual.
• We can not refer to their addresses.
• An object with a constructor (or destructor) can not be used as a member of a union.
• They make ‘implicit calls’ to the operators new and delete when memory allocation is required.
Remember, when a constructor is declared for a class, initialization of the class objects becomes
mandatory.
51. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
Types of Constructors:
1. Default constructor
2. Parameterized constructor
3. Default argument constructor
4. Copy constructor
5. Dynamic constructor
52. 1. Default Constructors
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A constructor that accept no parameter is called the default constructor.
• The default constructor for class A is A :: A( ).
• If no such constructor is defined, then the compiler supplies a default constructor.
• Therefore a statement such as :-
A a ;
It invokes the default constructor of the compiler to create the object “a”.
• The default constructor is also called non-argument constructor.
53. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
class circle
{
float radius;
public:
circle()
{
radius = 0;
}
};
In this example, the constructor function takes no
argument, and simply initializes radius to zero.
Non-arg constructor is also called as default
constructor.
class circle
{
float radius;
};
In this example, we have not defined any constructor, so
compiler will provide an empty body constructor to the
class, which is called as default constructor.
class circle
{
float radius;
public:
circle()
{
}
};
54. 2. Parameterized Constructors
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Sometimes it becomes necessary to initialize the various data elements of an objects with
different values when they are created.
• This is achieved by passing arguments to the constructor function when the objects are created.
• The constructors that can take arguments are called parameterized constructors.
• Using parameterized constructor we can initialize the various data elements of different objects
with different values when they are created.
55. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
class integer
{
int m, n;
public:
integer( int x, int y);
};
integer:: integer (int x, int y)
{
m=x;
n=y;
}
• We can call the parameterized constructor using
1. Implicit call
2. Explicit call
56. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
1. Implicit call
integer int1(0,100);
This method, sometimes called the shorthand method
2. Explicit call
integer int1 = integer(0,100);
57. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(int a, int b)
{
x=a;
y=b;
}
void display()
{
cout<<“(”<<x<<“,”<<y<<“)n”;
}
};
int main()
{
Point p1(1,1);
Point p2(5,10);
cout<<“Point p1 = ”;
p1.display();
cout<<“Point p2 = ”;
p2.display();
return 0;
}
Output:
Point p1 = (1,1)
Point p2 = (5,10)
58. 3. Default Argument Constructor
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• It is possible to define constructors with default arguments.
complex (float real, float imag = 0);
• The default value of the argument imag is zero.
• complex C1 (5.0);
assigns the value 5.0 to the real variable and 0.0 to imag.
• complex C2(2.0,3.0);
assigns the value 2.0 to real and 3.0 to imag.
• A : : A ( ) Default constructor
• A : : A (int = 0) Default argument constructor
• The default argument constructor can be called with either one argument or no arguments.
• When called with no arguments, it becomes a default constructor.
• When both these forms are used in a class, it causes ambiguity for a statement such as
A a;
• The ambiguity is whether to call A::A or A::A(int =0).
59. 4. Copy Constructor
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A copy constructor is used to declare and initialize an object from another object.
integer (integer & i) ;
• integer I2 ( I1 ) ;
would define the object I2 and at the same time initialize it to the values of I1.
• Another form of this statement is: integer I2 = I1;
• The process of initialization through a copy constructor is known as copy initialization.
• The statement
I2 = I1;
will not invoke the copy constructor.
• If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2,
member-by-member.
• A reference variable has been used as an argument to the copy constructor.
• We cannot pass the argument by value to a copy constructor.
60. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
using namespace std;
class code
{
int id;
public:
code() { } //constructor
code(int a) { id =a;} //parameterized constructor
code(code &x) //copy constructor
{
id =x.id; //copy in the value
}
void display(void)
{
cout<<id;
}
};
int main()
{
code A(100); //object A is created and initialized
code B(A); //copy constructor called
code C =A; //copy constructor called
code D; //D is created, not initialized
D=A; //copy constructed not called
cout<<“n id of A”;
A.display();
cout<<“n id of B”;
B.display();
cout<<“n id of C”;
C.display();
cout<<“n id of D”;
D.display();
return 0;
}
Output:
id of A:100
id of B:100
id of C:100
id of D:100
• A reference variable has been used as an argument to the
copy constructor.
• We cannot pass the argument by value to a copy
constructor.
• When no copy constructor is defined, the complier
supplies its own copy constructor.
61. 5. Dynamic Constructor
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The constructors can also 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 of the same size, thus resulting in the saving of memory.
• Allocate of memory to objects at the time of their construction is known as dynamic
constructors of objects.
• The memory is allocated with the help of new operator.
62. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
#include<string>
using namespace std;
class String
{
char *name;
int length;
public:
String()
{
length =0;
name = new char[length+1]; /* one extra for 0 */
}
String( char *s)
{
length=strlen(s);
name=new char [length+1];
strcpy(name,s);
}
void display(void)
{
cout<<name<<endl;
}
void join(string &a .string &b) ;
};
void String :: join(String &a, String &b)
{
length=a. length +b . length;
delete name;
name=new char[length+1]; /* dynamic allocation */
strcpy(name,a.name);
strcat(name,b.name);
}
int main( )
{
char * first = “Joseph” ;
String name1(first),name2(“Louis”),name3( “Lagrange”),s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
namel.display( );
name2.display( );
name3.display( );
s1.display( );
s2.display( );
return 0;
}
Output:
Joseph
Louis
Lagrange
Joseph Louis
Joseph Louis Lagrange
63. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• The program uses two constructors.
• The first is an empty constructor that allows us to declare an array of strings.
• The second constructor initializes the length of the string, alloactes necessary spaces for the string to be stored and
creates the string itself.
• Note that one additional character space is allocates to hold the end-of-string character ’0’.
• The member function join() concatenates two strings.
• It estimates the combined length of the string to be joined, allocates memory for the combined string and then
creates the same using the string functions strcpy() and strcat().
• The function join(), length and name are members of the object that calls the function.
• While a.length and a.name are members of the argument object a.
• The main() function program conctenates three strings into one string.
The output is as shown below:
Joseph Louis Lagrange
64. Handling of multiple constructor in class
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• C++ permits to use more than one constructors in a single class.
integer(); //No arguments
integer(int, int); //Two arguments
• In the first case, the constructor itself supplies the data values and no values are passed by
the calling program.
• In the second case, the function call passes the appropriate values from main().
• C++ permits us to use both these constructors in the same class.
65. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
using namespace std;
class integer
{
int m,n;
public:
integer() //constructor 1
{
m = 0;
n = 0;
}
integer(int a, int b) //constructor 2
{
m = a;
n = b;
}
integer(integer &i) //constructor 3
{
m = i.m;
n = i.n;
}
};
int main()
{
integer I1;
integer I2(20,40);
integer I3(I2);
return 0;
}
• This declares three constructors for an integer object. The first constructor
receive no arguments. The second receives two integer arguments and the third
receives one integer object as an argument.
• integer I1;
It would automatically invoke the first constructor and set m and n of I1 to zero.
• integer I2(20,40);
It would call second constructor which will initialize the data members m and n of
I2 to 20 and 40 respectively.
• integer I3(I2);
It would invoke the third constructor which copies the values of I2 into I3.
• The process of sharing the same name by two or more functions is referred to as
function overloading.
• Similarly, when more than one constructor function is defined in a class, we say
that the constructor is overloaded.
66. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
using namespace std;
class complex
{
float x,y;
public:
complex() { } //constructor no arg
complex(float a) { x=y=a; } //constructor-one arg
complex(float real, float imag) //constructor-two args
{
x = real;
y = imag;
}
friend complex sum(complex, complex);
friend void show(complex) ;
};
complex sum(complex c1, complex c2) //friend
{
complex c3;
c3.x = c1.x + c2.x;
c3.y = c1.y + c2.y;
return(c3);
}
void show(complex c) //friend
{
cout<<c.x<<“+j”<<c.y<<“n”;
}
Overloaded
Constructors:
int main()
{
complex A(2.7,3.5); //define & initialize
complex B(1.6); //define & initialize
complex C; //define
C = sum(A, B); //sum() is a friend
cout<<“A= ”;
show(A); //show() is also friend
cout<<“B= ”;
show(B);
cout<<“C= ”;
show(C);
//Another way to give initial values(second method)
complex P,Q,R;
P = complex(2.5, 3.9);
Q = complex(1.6, 2.5);
R = sum(P, Q);
cout<<“n”;
cout<<“P=”;
show(P);
cout<<“Q=”;
show(Q);
cout<<“R=”;
show(R);
return 0;
}
Output:
A = 2.7 + j3.5
B = 1.6 + j1.6
C = 4.3 + j5.1
P = 2.5 + j3.9
Q = 1.6 + j2.5
R = 4.1 + j6.4
67. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• There are three constructors in the class complex.
• The first constructor, which takes no arguments, is used to create objects which are not initialized.
• The second constructor, which takes one argument, is used to create objects and initialize them.
• The third constructor, which takes two argument, is used to create objects and initialize them to specific values.
• The second method of initializing values looks better.
• C + + compiler has an implicit constructor which creates objects, even though it was not defined in the class.
• This works well as long as we do not use any other constructor in the class.
• However, once we define a constructor, we must also define the “do-nothing” implicit constructor.
68. Destructors
Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A destructor, as the name implies, is used to destroy the objects that have been created by constructor.
• Like a constructor, the destructor is an member function whose name is the same as the class name
but is preceded by a tilde.
• Ex. The destructor for the class integer can be defined as shown below:
~integer() { }
• A destructor never takes any argument nor does it return any value.
• It will be invoked implicitly by the compiler upon exit from the program (or block or function as the
case may be) to clean up storage that is no longer accessible.
• It is a good practice to declare destructors in a program since it releases memory space for further use.
69. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• Whenever new is used to allocate memory in the constructor, we should use delete to free that memory.
• Ex. the destructor for the matrix class discussed above may be defined as follows:
matrix :: ~matrix()
{
for(int i = 0; i<d1; i++)
delete p[i];
delete p;
}
This is required because when the pointers to objects go out of scope, a destructor is not called implicitly.
70. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
#include<iostream>
using namespace std;
int count =0;
class test
{
public:
test()
{
count++;
cout<<“n Constructor Msg: Object number”<<count<< “created”;
}
~test()
{
cout<<“n Destructor Msg: Object number”<<count<<“destroyed”;
count--;
}
};
int main()
{
cout<<“Inside the main block…”;
cout<<“n Creating first object T1…”;
Test T1;
{
cout<<“nn Inside Block 1…”;
cout<<“n Creating two more objects T2 and T3”;
test T2, T3;
cout<<“n Leaving Block 1…”;
}
cout<<“n Back inside the main block…”;
return 0;
}
Output:
Inside the main block…
Creating first object T1…
Constructor Msg: Object number 1 created
Inside Block 1…
Creating two more objects T2 and T3
Constructor Msg: Object number 2 created
Constructor Msg: Object number 3 created
Leaving Block 1…
Destructor Msg: Object number 3 destroyed
Destructor Msg: Object number 2 destroyed
Back inside the main block…
Destructor Msg: Object number 1 destroyed
71. Department of E&TC Engineering, MCERC, Nashik
Object Oriented Programming
By- Ms. Dipali K. Pawar
ME(Comp) , BE(Comp)
• A class constructor is called every time an object is created.
• Similarly, as the program control leaves the current block the objects in the block start getting destroyed and
destructors are called for each one of them.
• Note that the objects are destroyed in the reverse order of their creation.
• Finally, when the main block is exited, destructors are called corresponding to the remaining objects present
inside main.