UNIT 3
Constructors and Destructors
- Explain Default Constructors
Answer: Default constructors do not take any parameters. If a default constructor is not provided by the programmer explicitly, then the compiler provides a implicit default constructor. In that case, the default values of the variables are 0.
A program that demonstrates default constructors is given as follows.
Example
#include <iostream>
Using namespace std;
Class A {
Private:
Int num1, num2 ;
Public:
A() {
Num1 = 5;
Num2 = 7;
}
Void display() {
Cout<<"num1 = "<< num1 <<endl;
Cout<<"num2 = "<< num2 <<endl;
}
};
Int main() {
Aobj;
Obj.display();
Return 0;
}
Output
Num1 = 5
Num2 = 7
In the above program, the class A contains a default constructor that initialises num1 and num2 as 5 and 7. It also contains a function display() that prints the value of num1 and num2. The code snippet for this is given as follows.
Class A {
Private:
Int num1, num2 ;
Public:
A() {
Num1 = 5;
Num2 = 7;
}
Void display() {
Cout<<"num1 = "<< num1 <<endl;
Cout<<"num2 = "<< num2 <<endl;
}
};
The function main() contains the object definition for an object of class type A. Then the function display() is called. This is shown below.
Aobj;
Obj.display();
2. Explain Parameterized Constructors
Answer: The parameterized constructors can take arguments to initialize an object when it is created. Parameters are added to a parameterized constructor just like they are added to a normal function. The parameterized constructors can be called implicitly or explicitly.
A program that demonstrates parameterized constructors is given as follows.
Example
#include <iostream>
Using namespace std;
Class A {
Private:
Int num1, num2 ;
Public:
A(int n1, int n2) {
Num1 = n1;
Num2 = n2;
}
Void display() {
Cout<<"num1 = "<< num1 <<endl;
Cout<<"num2 = "<< num2 <<endl;
}
};
Int main() {
A obj(3,8);
Obj.display();
Return 0;
}
Output
Num1 = 3
Num2 = 8
In the above program, the class A contains a parameterized constructor that initialises num1 and num2 with the values provided by n1 and n2. It also contains a function display() that prints the value of num1 and num2. The code snippet for this is given as follows.
Class A {
Private:
Int num1, num2 ;
Public:
A(int n1, int n2) {
Num1 = n1;
Num2 = n2;
}
Void display() {
Cout<<"num1 = "<< num1 <<endl;
Cout<<"num2 = "<< num2 <<endl;
}
};
The function main() contains the object definition for an object of class type A. Then the function display() is called. This is shown below.
A obj(3,8);
Obj.display();
3. Write an example to explain the concept of constructor
Answer: #include <iostream>
Using namespace std;
Class Line {
Public:
VoidsetLength( double len );
DoublegetLength( void );
Line(); // This is the constructor
Private:
Double length;
};
// Member functions definitions including constructor
Line::Line(void) {
Cout<< "Object is being created" <<endl;
}
Void Line::setLength( double len ) {
Length = len;
}
Double Line::getLength( void ) {
Return length;
}
// Main function for the program
Int main() {
Line line;
// set line length
Line.setLength(6.0);
Cout<< "Length of line : " <<line.getLength() <<endl;
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
4. Explain The Class Destructor
Answer: A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.
Following example explains the concept of destructor −
#include <iostream>
Using namespace std;
Class Line {
Public:
VoidsetLength( double len );
DoublegetLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
Private:
Double length;
};
// Member functions definitions including constructor
Line::Line(void) {
Cout<< "Object is being created" <<endl;
}
Line::~Line(void) {
Cout<< "Object is being deleted" <<endl;
}
Void Line::setLength( double len ) {
Length = len;
}
Double Line::getLength( void ) {
Return length;
}
// Main function for the program
Int main() {
Line line;
// set line length
Line.setLength(6.0);
Cout<< "Length of line : " <<line.getLength() <<endl;
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
Object is being deleted
5. What are the Characteristics of Constructors?
Answer:
- They should be declared in the public section.
- They are invoked automatically when the objects are created.
- They do not have return (data type) type not even void and there for they cannot return any values.
- They cannot be inherited, the a derived class can call the base class constructor.
- They make implicit calls to the operator new and delete when memory allocation is required.
- It is not possible to take the address of a constructor.
- An object of a class with a constructor cannot be a member of a union.
Note:-
Constructors and destructors have no return type, not even void.
A constructor for a class is needed so that the compiler automatically initializes an object as soon as it is created. A class constructor, if defined , is called whenever a program creates an object of that class.
6. What are the Types of Constructor?
Answer: In C++, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure.
There can be two types of constructors in C++.
- Default constructor
- Parameterized constructor
C++ Default Constructor
A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Let's see the simple example of C++ default Constructor.
- #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;
- }
Output:
Default Constructor Invoked
Default Constructor Invoked
C++ Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.
Let's see the simple example of C++ Parameterized Constructor.
#include <iostream>
Using namespace std;
Class Employee {
Public:
Int id;//data member (also instance variable)
String name;//data member(also instance variable)
Float salary;
Employee(inti, string n, float s)
{
Id = i;
Name = n;
Salary = s;
}
Void display()
{
Cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
Int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
Return 0;
}
Output:
101 Sonoo 890000
102 Nakul 59000
7. Write an Example of Constructor overloading
Answer: // C++ program to demonstrate constructor overloading
#include <iostream>
Using namespace std;
Class Person {
Private:
Int age;
Public:
// 1. Constructor with no arguments
Person() {
Age = 20;
}
// 2. Constructor with an argument
Person(int a) {
Age = a;
}
IntgetAge() {
Return age;
}
};
Int main() {
Person person1, person2(45);
Cout<< "Person1 Age = " << person1.getAge() <<endl;
Cout<< "Person2 Age = " << person2.getAge() <<endl;
Return 0;
}
Output
Person1 Age = 20
Person2 Age = 45
8. Explain Dynamic Initialization of an Object
Answer: The Dynamic Initialization of Objects means to initialize the data members of the class while creating the object. When we want to provide initial or default values to the data members while creating of object - we need to use dynamic initialization of objects.
Now, the question is how to achieve or implement dynamic initialization of objects?
It can be implemented by using parameterized constructors in C++.
Example:
Here, we have a class named "Student" which contains two private data members 1) rNo - to store roll number and 2) perc - to store percentage.
Program:
#include <iostream>
Usingnamespacestd;
//structure definition with private and public members
Struct Student {
Private:
IntrNo;
Float perc;
Public:
//constructor
Student(int r, float p)
{
RNo = r;
Perc = p;
}
//function to read details
Void read(void)
{
Cout<<"Enter roll number: ";
Cin>>rNo;
Cout<<"Enter percentage: ";
Cin>> perc;
}
//function to print details
Void print(void)
{
Cout<<endl;
Cout<<"Roll number: "<<rNo<<endl;
Cout<<"Percentage: "<< perc <<"%"<<endl;
}
};
//Main code
Intmain()
{
//reading roll number and percentage to initialize
//the members while creating object
Cout<<"Enter roll number to initialize the object: ";
Introll_number;
Cin>>roll_number;
Cout<<"Enter percentage to initialize the object: ";
Float percentage;
Cin>> percentage;
//declaring and initialize the object
Struct Student std(roll_number, percentage);
//print the value
Cout<<"After initializing the object, the values are..."<<endl;
Std.print();
//reading and printing student details
//by calling public member functions of the structure
Std.read();
Std.print();
Return0;
}
Output
Enter roll number to initialize the object: 101
Enter percentage to initialize the object: 84.02
After initializing the object, the values are...
Roll number: 101
Percentage: 84.02%
Enter roll number: 102
Enter percentage: 87
Roll number: 102
Percentage: 87%
9. What is Symbolic Constants?
Answer: Symbolic constant is a way of defining a variable constant whose value cannot be changed. It is done by using the keyword const.
For example
constint c=5;
In C symbolic constant can be achieved by the use of #define.
For example,
#define PI=3.142;
When this statement is compiled, the pre-processor(#) will replace all the occurrence of PI with 3.142, which is then compiled into executable format.
A problem with this was the we cannot use any normal variable with same name PI throughout the program otherwise it will be replaced by its constant value. So this problem is solved in C++, by the use of const qualifier. The scoping of const values differs. A const in C++ is default to the internal linkage and therefore, it is local to the file where is is declared. While in C, constants values are global in nature. They are visible outside the file which they are declared. They can be made local by declaring them as static. To access the const value from another file we must explicitly define it as extern in C++.
For example
extern const total=100;
Symbolic constant can also be defined using enumeration.
For example,
enum{n1,n2};
The enumerator n1 and n2 can be assigned constant value in following way:
const n1=1;
const n2=70;
10. Explain destructor.
Answer: A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde sign (~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.
C++ Constructor and Destructor Example
Let's see an example of constructor and destructor in C++ which is called automatically.
- #include <iostream>
- Using namespace std;
- Class Employee
- {
- Public:
- Employee()
- {
- Cout<<"Constructor Invoked"<<endl;
- }
- ~Employee()
- {
- Cout<<"Destructor Invoked"<<endl;
- }
- };
- Int main(void)
- {
- Employee e1; //creating an object of Employee
- Employee e2; //creating an object of Employee
- Return 0;
- }
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
|
- If a destructor is present, rewrite that to be the class finalizer.
- If a Dispose() method is present, rewrite that into the class destructor.
- If a destructor is present but there is no Dispose() method, retain the destructor while carrying out the first item.
In moving your code from Managed Extensions to the new syntax, it is possible to miss performing this transformation. If the application depended in some way on the execution of associated finalization methods, then the behavior of the application will silently differ.