EXP-5 Constructors and Destructors
EXP-5 Constructors and Destructors
#include <iostream>
using namespace std;
class Person{
public:
// declaring constructor
Person()
{
cout<<"Default constructor is called"<<endl;
name = "student";
age = 12;
}
};
int main()
{
// creating object of class using default constructor
Person obj;
return 0;
}
Output
Default constructor is called
Name of current object: student
Age of current object: 12
#include <iostream>
using namespace std;
class Person{
public:
Person(int person_age)
{
cout<<"Constructor to set age is called"<<endl;
name = "Student";
age = person_age;
}
};
int main()
{
// creating objects of class using parameterized constructor
Person obj1("First person");
Person obj2(25);
public:
// Parameterized constructor
student(int, string, double);
// Copy constructor
student(student& t)
{
rno = t.rno;
name = t.name;
fee = t.fee;
cout << "Copy Constructor Called" << endl;
}
// Function to display student details
void display();
};
int main()
{
// Create student object with parameterized constructor
student s(1001, "Manjeet", 10000);
s.display();
return 0;
}
Output
1001 Manjeet 10000
Copy Constructor Called
1001 Manjeet 10000
#include <iostream>
using namespace std;
class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }
// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
main()
{
Test t;
return 0;
}
Output
Constructor executed
Destructor executed