CPP - Unit II - Constructor and Distructor
CPP - Unit II - Constructor and Distructor
Subject Code :2
Semester : II
Prepared by : Mrs.G.Gokilavani
Assistant Professor
Department of Information Technology
KG College of Arts and Science
Unit II
Constructor and destructor with
static members
Constructor and destructor with static members
#include<iostream.h>
#include<conio.h>
class exam{
private:
int sno,mark1,mark2;
public:
exam( ){ //constructor
sno=mark1=mark2=100;
}
void showdata() {
cout<<sno<<mark1<<mark2
}
~exam(){ //Destructor
cout<<"destructo is invoked";
}};
int main(){
exam e;
e.showdata();
exam e1(1,90,90);
clrscr();
e1.showdata();
return 0;
}
Output:
Sno = 100 Mark1 = 100 Mark2 =100
Sno = 100 Mark1 = 100 Mark2 =100
destructor is invoked
Characteristic of constructors and
Destructors
Characteristic of constructors and
Destructors
Characteristic of constructors and
Destructors
Constructors with default Arguments
• A Default constructor is a type of constructor which doesn’t take any argument and has no parameters.
• Example:
#include <iostream>
using namespace std;
class test {
public:
int y, z;
test()
{
y = 7;
z = 13;
}
};
int main()
{
test a;
cout <<"the sum is: "<< a.y+a.z;
return 1;
}
• Output: the sum is: 20
Constructors with default Arguments
•Explanation:
–The above program is a basic demo of a constructor in c++. We have a class test,
with two data members of type int called y and z. Then we have a default
constructor, which assigns 7 and 13 to the variables y and z respectively.
–The above program is a basic demo of a constructor in c++. We have a class test,
with two data members of type int called y and z. Then we have a default
constructor, which assigns 7 and 13 to the variables y and z respectively.
–The main function has an object of class test called a. When this object is created
the constructor is called and the variables y and z are given values. The main
function has a cout statement or a print statement. In this statement, the sum is
printed. With respect to the object of the class, we access the public members of
the class, that is, a.y gives the value of y and the same for z. We display the sum of
y and z.
–The default constructor works this way. When we do not provide a default
constructor, the compiler generates a default constructor which does not operate.
Constructor with Arguments
• Explanation:
• In this program, we have created a class Person that has a single
variable age.
• We have also defined two constructors Person() and Person(int a):
• When the object person1 is created, the first constructor is called
because we have not passed any argument. This constructor
initializes age to 20.
• When person2 is created, the second constructor is called since we
have passed 45 as an argument. This constructor
initializes age to 45.
• The function getAge() returns the value of age, and we use it to
print the age of person1 and person2.
Copy constructors