c++
1. If a class having dynamically allocated members didn't define its own destructor, what possible problem(s) could arise?
2. If a class having dynamically allocated members didn't define its own copy constructor, what possible problem(s) could arise?
3. If a class having dynamically allocated members didn't define its own assignment operator, what possible problem(s) could arise?
Constructor:
In object-oriented programming(C++), a constructor is a special method of the class that has the same name as the class name and it initializes the data member at object creation time.
Destructor:
When an object goes out of scope then the destructor method is called automatically and this method deletes the object by releasing the memory.
1.
If a class having dynamically allocated members didn't define its own destructor then the compiler will define it implicitly.
For example:
#include <iostream>
using namespace std;
class ABC
{
int a;
public:
//default constructor
ABC()
{
a = 0;
}
//parameterize constructor
ABC(int x)
{
a = x;
}
};
int main()
{
ABC();
ABC a;
//call destructor
a.~ABC();
return 0;
}
In the above program, the constructor is defined but destructor is not defined but this program will execute successfully.
2.
If a class having dynamically allocated members didn't define its own copy constructor, then the compiler will define it implicitly.
A copy constructor is a special type of constructor that creates an object and initializes it with another object of the same class.
But, we must define a copy constructor if the class is having the pointer variable and has dynamic memory allocation.
The default copy constructor does only the shallow copy but the defined copy constructor can make a deep copy.
3.
If a class having dynamically allocated members didn't define its own assignment operator then the compiler will define it implicitly.
For example:
#include <iostream>
using namespace std;
class ABC
{
int a;
public:
//default constructor
ABC()
{
a = 0;
}
//parameterize constructor
ABC(int x)
{
a = x;
}
};
int main()
{
//create object
ABC a(10);
ABC b;
b = a;
return 0;
}
In the above program, the assignment operator is not defined but it will work correctly.
Both of the objects will point to different memory locations because only values are copied.
Get Answers For Free
Most questions answered within 1 hours.