This section contains the C++ find output programs with their explanations on C++ Constructor and Destructor (set 3).
Program 1:
#include <iostream>
using namespace std;
class Sample {
private:
int X;
public:
Sample()
{
X = 0;
}
void set(int x)
{
X = x;
}
void print()
{
cout << X << endl;
}
};
int main()
{
Sample S[2] = { Sample(), Sample() };
S[0].set(10);
S[1].set(20);
S[0].print();
S[1].print();
return 0;
}
Program 2:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Sample {
private:
int X;
public:
Sample()
{
X = 0;
cout << "Constructor called";
}
void set(int x)
{
X = x;
}
void print()
{
cout << X << endl;
}
};
int main()
{
Sample* S;
S = (Sample*)malloc(sizeof(Sample));
S.set(10);
S.print();
return 0;
}
Program 3:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Sample {
private:
int X;
public:
Sample()
{
X = 0;
cout << "Constructor called";
}
void set(int x)
{
X = x;
}
void print()
{
cout << X << endl;
}
};
int main()
{
Sample* S;
S = (Sample*)malloc(sizeof(Sample));
(*S).set(10);
(*S).print();
return 0;
}
Answer Program 1:
Output:
Explanation:
In the above program, we created a class Sample with data member X, default constructor, set() and print() member functions.
Now coming to the main() function, here we created an array of objects that instantiated by default constructor. And then called set() and print() function using an array of objects then it will print above output.
Answer Program 2:
Output:
Explanation:
The above program will generate an error, because, S is a pointer, and we used Dot (.) Operator to call set() and print() member functions instead of referential operator (->).
Answer Program 3:
Output:
Explanation:
In the above program, we created a class Sample with data member X, default constructor, set() and print() member functions.
Coming to the main() function, here we declared a pointer of the class Sample and instantiate by malloc() function and then called set() and print() functions using the pointer. But, when we use malloc() function it will not call the constructor.
need an explanation for this answer? contact us directly to get an explanation for this answer