C++ Programming - Constructors and Destructors - Discussion
Discussion Forum : Constructors and Destructors - General Questions (Q.No. 35)
35.
How many times a constructor is called in the life-time of an object?
Discussion:
5 comments Page 1 of 1.
Amit shinde said:
3 years ago
#include<iostream>
using namespace std;
class complex
{
public:
int num1,num2;
complex ()
{
}
complex (int a, int b)
{
num1=a;
num2=b;
}
};
int main()
{
complex obj;
obj=complex(4,5);
cout<<obj.num1<<" "<<obj.num2<<endl;
obj=complex(7,8);
cout<<obj.num1<<" "<<obj.num2;
return 0;
}
Here, Constructor is called two times.
using namespace std;
class complex
{
public:
int num1,num2;
complex ()
{
}
complex (int a, int b)
{
num1=a;
num2=b;
}
};
int main()
{
complex obj;
obj=complex(4,5);
cout<<obj.num1<<" "<<obj.num2<<endl;
obj=complex(7,8);
cout<<obj.num1<<" "<<obj.num2;
return 0;
}
Here, Constructor is called two times.
Peter said:
7 years ago
class A
{
public:
int a;
A(){ a = 5; }
};
int main()
{
A a;
a.a = 6;
new (&a) A();
cout << a.a; // prints 5
}
Does this count as creating a new object?
Otherwise, D is correct.
{
public:
int a;
A(){ a = 5; }
};
int main()
{
A a;
a.a = 6;
new (&a) A();
cout << a.a; // prints 5
}
Does this count as creating a new object?
Otherwise, D is correct.
Vimal said:
8 years ago
But it depends upon the how many objects we are created. On that depends how many times constructor be called.
IshanG said:
10 years ago
Life time of the object means from when it is created till the end of it's scope. Whenever an object gets created, the constructor is called. Since the question implies that it is a single object, hence constructor will be called only once in the lifetime of that object.
Sravan said:
1 decade ago
Anyone please work it out, I didn't get this.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers