Session 13
Session 13
AND PROGRAMMING
Session 12
– initializes the object of the class and allocates the memory location for an
object,
– the function has the name as the class name, known for creating the object,
called when the instance of the class created.
• Destructor also has the same name as the class name,
• Default constructor
• Copy constructor
4
Constructor
• It is a special kind of class member function that is automatically called when an
object of that class is instantiated.
• Constructors are typically used to initialize member variables of the class to
appropriate default or user-provided values.
• The constructor is like normal function within the class and the compiler calls it
automatically when we create a new object of that class.
• A method is a collection of statements that perform some specific task and return the
result to the caller. A method can perform some specific task without returning anything.
9
Method Vs Constructor
• Used to define particular task for
• Used to initialize the data members
execution
• Constructor has same name as the class
• Method can have same name as class name
name or different name based on the • Constructor is automatically called when
requirement an object is created
compiler
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Parameterized Constructors
• A constructor that takes
arguments are called
parameterized constructors
•
Copy constructor:
• When we initialize the object with another existing object of the same class type.
For example, Student s1 = s2, where Student is the class.
• When the object of the same class type is passed by value as an argument.
• When the function returns the object of the same class type by value.
Example for copy constructor
~HelloWorld() return 0;
{ }
cout<<"Destructor is called"<<endl;
}
output
//Member function
void display() Constructor is called
{ Hello World!
cout<<"Hello World!"<<endl; Destructor is called
Destructor }
};
Destructor rules
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any
parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a
default destructor and inserts it into your code.
Example Program
class Student // copy constructor
{ Student (const Student &s)
public: {
int rollno; rollno = s.rollno;
string name; name = s.name;
Student() //Default constructor }
{ rollno = 0; }; // end of class
name = "None";
} int main()
Student(int x) // parameterized {
{ rollno = x; Student A1();
name = "None"; Student A(10);
} Student B=A;
}