Practical C++ Programs Based on Constructors and Destructors with Output
1. C++ Program to Demonstrate Different Types of Constructors
C++ supports different constructor forms, including default constructors, parameterized constructors, and copy constructors. These constructors are used to initialize objects in different ways.
C++ में अलग-अलग constructor forms उपलब्ध हैं, जिनमें Default Constructor, Parameterized Constructor और Copy Constructor शामिल हैं। इनका उपयोग objects को अलग-अलग तरीकों से initialize करने के लिए किया जाता है।
Program
#include <iostream>
using namespace std;
class Student {
private:
int rollNo;
public:
// Default constructor
Student() {
rollNo = 0;
}
// Parameterized constructor
Student(int r) {
rollNo = r;
}
// Copy constructor
Student(const Student& s) {
rollNo = s.rollNo;
}
void display() const {
cout << "Roll Number: " << rollNo << endl;
}
};
int main() {
Student s1;
Student s2(101);
Student s3(s2);
cout << "Default Constructor:" << endl;
s1.display();
cout << "\nParameterized Constructor:" << endl;
s2.display();
cout << "\nCopy Constructor:" << endl;
s3.display();
return 0;
}Output
Default Constructor:
Roll Number: 0
Parameterized Constructor:
Roll Number: 101
Copy Constructor:
Roll Number: 101Explanation
Student()is a default constructor that initializes the roll number to 0.Student(int r)is a parameterized constructor that initializes the roll number with the supplied value.Student(const Student& s)is a copy constructor that initializes a new object using an existing object.Three objects are created using three different constructor forms.
व्याख्या:
Student()एक Default Constructor है, जो roll number को 0 से initialize करता है।Student(int r)एक Parameterized Constructor है, जो दिए गए value से roll number initialize करता है।Student(const Student& s)एक Copy Constructor है, जो existing object की सहायता से नए object को initialize करता है।इस program में तीन अलग-अलग constructor forms का उपयोग करके तीन objects बनाए गए हैं।
2. C++ Program to Demonstrate Constructor Overloading
Constructor overloading means defining multiple constructors in the same class with different parameter lists. The compiler selects the appropriate constructor according to the arguments supplied during object creation.
Constructor Overloading का अर्थ है एक ही class में अलग-अलग parameter lists वाले multiple constructors define करना। Object create करते समय दिए गए arguments के अनुसार compiler appropriate constructor select करता है।
Program
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int breadth;
public:
// Default constructor
Rectangle() {
length = 0;
breadth = 0;
}
// One-parameter constructor
Rectangle(int side) {
length = side;
breadth = side;
}
// Two-parameter constructor
Rectangle(int l, int b) {
length = l;
breadth = b;
}
void area() const {
cout << "Area: " << length * breadth << endl;
}
};
int main() {
Rectangle r1;
Rectangle r2(5);
Rectangle r3(10, 6);
cout << "Default Constructor:" << endl;
r1.area();
cout << "\nOne Parameter Constructor:" << endl;
r2.area();
cout << "\nTwo Parameter Constructor:" << endl;
r3.area();
return 0;
}Output
Default Constructor:
Area: 0
One Parameter Constructor:
Area: 25
Two Parameter Constructor:
Area: 60Explanation
The first constructor initializes both dimensions to zero.
The second constructor accepts one value and creates a square.
The third constructor accepts two values and creates a rectangle.
The compiler selects the constructor based on the number of arguments.
व्याख्या:
पहला constructor दोनों dimensions को zero से initialize करता है।
दूसरा constructor एक value स्वीकार करता है और square बनाता है।
तीसरा constructor दो values स्वीकार करता है और rectangle बनाता है।
Compiler arguments की संख्या के आधार पर appropriate constructor select करता है।
3. C++ Program to Demonstrate Copy Constructor
A copy constructor creates a new object by initializing it with an existing object of the same class.
Its commonly used syntax is:
ClassName(const ClassName& object);Copy Constructor, उसी class के existing object की सहायता से एक नया object initialize करता है।
इसका commonly used syntax है:
ClassName(const ClassName& object);Program
#include <iostream>
using namespace std;
class Employee {
private:
int id;
float salary;
public:
Employee(int i, float s) {
id = i;
salary = s;
}
// Copy constructor
Employee(const Employee& e) {
id = e.id;
salary = e.salary;
}
void display() const {
cout << "Employee ID: " << id << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
Employee e1(101, 35000);
Employee e2(e1);
cout << "Original Object:" << endl;
e1.display();
cout << "\nCopied Object:" << endl;
e2.display();
return 0;
}Output
Original Object:
Employee ID: 101
Salary: 35000
Copied Object:
Employee ID: 101
Salary: 35000Explanation
The first object
e1is initialized using the parameterized constructor.The second object
e2is initialized using the copy constructor.The copy constructor copies the values of
idandsalaryfrome1toe2.Both objects contain the same data, but they are separate objects.
व्याख्या:
पहले object
e1को Parameterized Constructor की सहायता से initialize किया गया है।दूसरे object
e2को Copy Constructor की सहायता से initialize किया गया है।Copy Constructor,
e1सेidऔरsalaryकी values कोe2में copy करता है।दोनों objects में समान data है, लेकिन वे अलग-अलग objects हैं।
4. C++ Program to Demonstrate Destructor
A destructor is a special member function that is automatically called when an object is destroyed. Its name is the class name preceded by a tilde (~).
A destructor does not have a return type and does not accept parameters.
Destructor एक special member function है, जिसे object destroy होने पर automatically call किया जाता है। इसका नाम class name के पहले tilde (~) लगाकर बनाया जाता है।
Destructor का कोई return type नहीं होता और यह parameters accept नहीं करता।
Program
#include <iostream>
using namespace std;
class Demo {
public:
Demo() {
cout << "Constructor called." << endl;
}
~Demo() {
cout << "Destructor called." << endl;
}
};
int main() {
cout << "Entering main function." << endl;
{
Demo obj;
cout << "Object is being used." << endl;
}
cout << "Object has been destroyed." << endl;
return 0;
}Output
Entering main function.
Constructor called.
Object is being used.
Destructor called.
Object has been destroyed.Explanation
The program enters the
main()function.An object
objis created inside a block.Its constructor is called automatically.
When execution leaves the block,
objis destroyed.The destructor is called automatically before the next statement executes.
व्याख्या:
Program,
main()function में enter करता है।एक block के अंदर
objobject create किया जाता है।इसका constructor automatically call होता है।
जब program block से बाहर आता है, तब
objdestroy हो जाता है।अगला statement execute होने से पहले destructor automatically call होता है।
5. C++ Program to Add Two Complex Numbers Using Multiple Constructors
A complex number consists of two parts: a real part and an imaginary part. It is generally represented as:
[
z = a + bi
]
Here, a represents the real part, b represents the imaginary part, and i is the imaginary unit.
Two complex numbers are added by separately adding their real and imaginary parts.
Complex Number के दो parts होते हैं: Real Part और Imaginary Part। इसे सामान्यतः निम्न रूप में represent किया जाता है:
[
z = a + bi
]
यहाँ a Real Part, b Imaginary Part और i imaginary unit को represent करता है।
दो complex numbers को जोड़ने के लिए उनके real parts और imaginary parts को अलग-अलग add किया जाता है।
Program
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
// Default constructor
Complex() {
real = 0;
imag = 0;
}
// Parameterized constructor
Complex(float r, float i) {
real = r;
imag = i;
}
// Copy constructor
Complex(const Complex& c) {
real = c.real;
imag = c.imag;
}
Complex add(const Complex& c) const {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
void display() const {
cout << real;
if (imag >= 0)
cout << " + " << imag << "i";
else
cout << " - " << -imag << "i";
cout << endl;
}
};
int main() {
Complex c1(3, 4);
Complex c2(2, 5);
Complex c3 = c1.add(c2);
cout << "First Complex Number: ";
c1.display();
cout << "Second Complex Number: ";
c2.display();
cout << "Sum of Complex Numbers: ";
c3.display();
return 0;
}Output
First Complex Number: 3 + 4i
Second Complex Number: 2 + 5i
Sum of Complex Numbers: 5 + 9iExplanation
The class contains two data members:
realandimag.The default constructor initializes both parts to zero.
The parameterized constructor initializes a complex number with two supplied values.
The copy constructor initializes a new complex object from an existing object.
The
add()function adds the corresponding real and imaginary parts.The resulting complex number is returned as an object.
व्याख्या:
Class में दो data members
realऔरimagहैं।Default Constructor दोनों parts को zero से initialize करता है।
Parameterized Constructor दिए गए दो values से complex number initialize करता है।
Copy Constructor existing object से नया complex object initialize करता है।
add()function corresponding real और imaginary parts को जोड़ता है।Resulting complex number को object के रूप में return किया जाता है।
6. C++ Program to Demonstrate Complex Number Addition Using a Class
In this program, two complex numbers are added using a class and an addition member function. It demonstrates how data and operations can be combined inside a class.
इस program में class और addition member function की सहायता से दो complex numbers को add किया गया है। यह दर्शाता है कि class के अंदर data और operations को किस प्रकार combine किया जा सकता है।
Program
#include <iostream>
using namespace std;
class Complex {
private:
int real;
int imag;
public:
void getData(int r, int i) {
real = r;
imag = i;
}
Complex add(const Complex& c) const {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1, c2, c3;
c1.getData(5, 3);
c2.getData(4, 2);
c3 = c1.add(c2);
cout << "First Complex Number: ";
c1.display();
cout << "Second Complex Number: ";
c2.display();
cout << "Addition Result: ";
c3.display();
return 0;
}Output
First Complex Number: 5 + 3i
Second Complex Number: 4 + 2i
Addition Result: 9 + 5iExplanation
Three objects
c1,c2, andc3are created.The
getData()function initializes the real and imaginary parts of the first two objects.The
add()function adds the corresponding parts of both complex numbers.The result is stored in
c3.The
display()function displays all three complex numbers.
व्याख्या:
तीन objects
c1,c2औरc3create किए गए हैं।getData()function पहले दो objects के real और imaginary parts initialize करता है।add()function दोनों complex numbers के corresponding parts को add करता है।Result को
c3में store किया जाता है।display()function तीनों complex numbers को display करता है।
7. C++ Program to Add Two Rational Numbers Using Multiple Constructors
A rational number is a number that can be expressed in the form:
[
\frac{p}{q}, \quad q \neq 0
]
Here, p is the numerator and q is the denominator.
To add two rational numbers, we use the following formula:
\frac{ad+bc}{bd}
]
A class can use multiple constructors to initialize rational numbers in different ways.
Rational Number वह संख्या है जिसे निम्न रूप में express किया जा सकता है:
[
\frac{p}{q}, \quad q \neq 0
]
यहाँ p Numerator और q Denominator है।
दो rational numbers को add करने के लिए निम्न formula का उपयोग किया जाता है:
\frac{ad+bc}{bd}
]
एक class में multiple constructors का उपयोग करके rational numbers को अलग-अलग तरीकों से initialize किया जा सकता है।
Program
#include <iostream>
using namespace std;
class Rational {
private:
int numerator;
int denominator;
public:
// Default constructor
Rational() {
numerator = 0;
denominator = 1;
}
// Parameterized constructor
Rational(int n, int d) {
numerator = n;
denominator = d;
}
// Copy constructor
Rational(const Rational& r) {
numerator = r.numerator;
denominator = r.denominator;
}
Rational add(const Rational& r) const {
Rational temp;
temp.numerator =
numerator * r.denominator +
r.numerator * denominator;
temp.denominator =
denominator * r.denominator;
return temp;
}
void display() const {
cout << numerator << "/" << denominator << endl;
}
};
int main() {
Rational r1(1, 2);
Rational r2(1, 3);
Rational r3 = r1.add(r2);
cout << "First Rational Number: ";
r1.display();
cout << "Second Rational Number: ";
r2.display();
cout << "Sum of Rational Numbers: ";
r3.display();
return 0;
}Output
First Rational Number: 1/2
Second Rational Number: 1/3
Sum of Rational Numbers: 5/6Explanation
The
Rationalclass contains numerator and denominator data members.The default constructor initializes the rational number to
0/1.The parameterized constructor initializes the numerator and denominator.
The copy constructor copies an existing rational number.
The
add()function applies the rational addition formula.The resulting fraction is returned as a new object.
व्याख्या:
Rationalclass में numerator और denominator data members हैं।Default Constructor rational number को
0/1से initialize करता है।Parameterized Constructor numerator और denominator को initialize करता है।
Copy Constructor existing rational number को copy करता है।
add()function rational addition formula का उपयोग करता है।Resulting fraction को नए object के रूप में return किया जाता है।
Note: This program does not simplify the resulting fraction. For example, a result of 2/4 would be displayed as 2/4, not 1/2.
ध्यान दें: यह program resulting fraction को simplify नहीं करता। उदाहरण के लिए, यदि result 2/4 है, तो यह 1/2 के स्थान पर 2/4 ही display करेगा।
8. C++ Program to Demonstrate Shallow Copy and Deep Copy
Shallow copy and deep copy are two ways of copying objects in C++. They are particularly important when a class contains pointers and dynamically allocated memory.
Shallow Copy: Copies pointer values, so two objects may refer to the same dynamically allocated memory.
Deep Copy: Creates separate memory for the copied object and copies the actual data.
Shallow Copy और Deep Copy, C++ में objects को copy करने के दो तरीके हैं। ये विशेष रूप से तब महत्वपूर्ण होते हैं जब class में pointers और dynamically allocated memory का उपयोग किया जाता है।
Shallow Copy: Pointer values को copy करता है, इसलिए दो objects एक ही dynamically allocated memory को refer कर सकते हैं।
Deep Copy: Copied object के लिए अलग memory create करता है और actual data को copy करता है।
Program
#include <iostream>
using namespace std;
class Shallow {
public:
int* data;
Shallow(int value) {
data = new int(value);
}
};
class Deep {
public:
int* data;
Deep(int value) {
data = new int(value);
}
// Deep copy constructor
Deep(const Deep& obj) {
data = new int(*obj.data);
}
~Deep() {
delete data;
}
};
int main() {
// Shallow Copy Demonstration
Shallow s1(10);
Shallow s2 = s1;
cout << "Shallow Copy:" << endl;
cout << "s1 value: " << *s1.data << endl;
cout << "s2 value: " << *s2.data << endl;
*s2.data = 20;
cout << "After modifying s2:" << endl;
cout << "s1 value: " << *s1.data << endl;
cout << "s2 value: " << *s2.data << endl;
delete s1.data;
s1.data = nullptr;
s2.data = nullptr;
// Deep Copy Demonstration
Deep d1(30);
Deep d2 = d1;
cout << "\nDeep Copy:" << endl;
cout << "d1 value: " << *d1.data << endl;
cout << "d2 value: " << *d2.data << endl;
*d2.data = 40;
cout << "After modifying d2:" << endl;
cout << "d1 value: " << *d1.data << endl;
cout << "d2 value: " << *d2.data << endl;
return 0;
}Output
Shallow Copy:
s1 value: 10
s2 value: 10
After modifying s2:
s1 value: 20
s2 value: 20
Deep Copy:
d1 value: 30
d2 value: 30
After modifying d2:
d1 value: 30
d2 value: 40Explanation
Shallow Copy:
s1dynamically allocates memory for an integer.s2 = s1performs the compiler-generated memberwise copy.Both pointers refer to the same memory location.
Modifying the value through
s2also changes the value observed throughs1.
Deep Copy:
d1dynamically allocates memory for an integer.The custom copy constructor allocates separate memory for
d2.The value is copied into the new memory location.
Modifying
d2does not affectd1.
Shallow Copy:
s1एक integer के लिए dynamically memory allocate करता है।s2 = s1compiler-generated memberwise copy करता है।दोनों pointers एक ही memory location को refer करते हैं।
s2के माध्यम से value modify करने परs1में भी modified value दिखाई देती है।
Deep Copy:
d1एक integer के लिए dynamically memory allocate करता है।Custom Copy Constructor,
d2के लिए अलग memory allocate करता है।Value को नई memory location में copy किया जाता है।
d2को modify करने परd1प्रभावित नहीं होता।
Note: The shallow-copy demonstration intentionally uses a class without an owning destructor. The program manually deletes the shared allocation exactly once. The deep-copy class owns its allocation and releases it through its destructor. For production code, implement the required copy-assignment and move operations as appropriate, or prefer RAII types such as std::vector, std::string, and smart pointers.
ध्यान दें: Shallow Copy वाले demonstration में जानबूझकर owning destructor नहीं बनाया गया है। Program shared allocation को manually केवल एक बार delete करता है। Deep Copy class अपनी allocated memory का ownership रखती है और destructor के माध्यम से उसे release करती है। Production code में आवश्यकता के अनुसार copy-assignment और move operations implement करें या std::vector, std::string और smart pointers जैसे RAII types को prefer करें।
9. C++ Program to Demonstrate the Order of Constructor and Destructor Execution
In C++, constructors and destructors are executed in a specific order.
For local objects:
Constructors are called in the order in which objects are created.
Destructors are called in the reverse order of object destruction.
For class members:
Member objects are constructed in their declaration order.
Member objects are destroyed in reverse declaration order.
C++ में Constructors और Destructors एक specific order में execute होते हैं।
Local objects के लिए:
Constructors, objects के creation order में call होते हैं।
Destructors, objects के destruction के reverse order में call होते हैं।
Class members के लिए:
Member objects, उनकी declaration order में construct होते हैं।
Member objects, reverse declaration order में destroy होते हैं।
Program
#include <iostream>
using namespace std;
class Demo {
private:
int value;
public:
Demo(int v) {
value = v;
cout << "Constructor called for "
<< value << endl;
}
~Demo() {
cout << "Destructor called for "
<< value << endl;
}
};
int main() {
cout << "Main function started." << endl;
Demo obj1(1);
Demo obj2(2);
Demo obj3(3);
cout << "Main function ending." << endl;
return 0;
}Output
Main function started.
Constructor called for 1
Constructor called for 2
Constructor called for 3
Main function ending.
Destructor called for 3
Destructor called for 2
Destructor called for 1Explanation
First,
obj1is created and its constructor is called.Next,
obj2is created and its constructor is called.Then,
obj3is created and its constructor is called.When
main()ends, local objects are destroyed in reverse order.Therefore, the destructor of
obj3is called first, followed byobj2andobj1.
व्याख्या:
सबसे पहले
obj1create होता है और उसका constructor call होता है।इसके बाद
obj2create होता है और उसका constructor call होता है।फिर
obj3create होता है और उसका constructor call होता है।जब
main()समाप्त होता है, तब local objects reverse order में destroy होते हैं।इसलिए सबसे पहले
obj3का destructor call होता है, उसके बादobj2औरobj1का destructor call होता है।
Frequently Asked Questions (FAQs)
1. What is a constructor in C++?
A constructor is a special member function that initializes an object when it is created.
Constructor एक special member function है, जो object create होने पर उसे initialize करता है।
2. What is a destructor in C++?
A destructor is a special member function that is automatically called when an object is destroyed. It is commonly used for cleanup and resource management.
Destructor एक special member function है, जिसे object destroy होने पर automatically call किया जाता है। इसका उपयोग cleanup और resource management के लिए किया जाता है।
3. What are the main types of constructors in C++?
Common constructor forms include default constructors, parameterized constructors, and copy constructors. C++ also supports move constructors.
C++ में common constructor forms में Default Constructor, Parameterized Constructor और Copy Constructor शामिल हैं। C++ में Move Constructor भी उपलब्ध है।
4. What is constructor overloading?
Constructor overloading means defining multiple constructors in a class with different parameter lists.
Constructor Overloading का अर्थ है एक class में अलग-अलग parameter lists वाले multiple constructors define करना।
5. Can a constructor return a value?
No. A constructor does not have a return type, not even void.
नहीं। Constructor का कोई return type नहीं होता, यहाँ तक कि void भी नहीं।
6. Can a destructor be overloaded?
No. A class can have only one destructor, and it cannot accept parameters.
नहीं। किसी class में केवल एक destructor हो सकता है और यह parameters accept नहीं कर सकता।
7. What is the difference between a copy constructor and copy assignment operator?
A copy constructor initializes a new object from an existing object. A copy assignment operator copies the contents of an existing object into an already initialized object.
Copy Constructor, existing object से नए object को initialize करता है। Copy Assignment Operator, पहले से initialized object में existing object का data copy करता है।
8. What is the difference between shallow copy and deep copy?
Shallow copy copies pointer values, which may cause multiple objects to share the same memory. Deep copy creates separate memory and copies the actual data.
Shallow Copy pointer values को copy करता है, जिससे multiple objects एक ही memory share कर सकते हैं। Deep Copy अलग memory create करके actual data copy करता है।
9. In which order are destructors called?
For local objects in the same scope, destructors are called in reverse order of their completed initialization.
एक ही scope के local objects के destructors, उनके completed initialization के reverse order में call होते हैं।
Comments
Post a Comment