B
bharath.donnipad
Hi All,
I was going through a c++ manual in msdn site
"http://msdn2.microsoft.com/en-us/library/kewsb8ba.aspx". There there
was a small note on usage of new operator :
"When new is used to allocate memory for a C++ class object, the
object's constructor is called after the memory is allocated."
So, I got a doubt and quickly executed below program. Its o/p is : base
#include <iostream.h>
#include <stdlib.h>
class base
{
int *p;
public:
base()
{
p=new int[1000];
std::cout<<"base";
}
};
int main()
{
base *bptr=new base;
delete bptr;
system("PAUSE");
return 0;
}
My doubt here is on "base *bptr=new base;" statement.
1. if iam right, to create an object here compiler uses ctr "base()".
So, ctr gets executed once. Since I used new here as per msdn manual
statement constructor should be called again & "base" should be printed
again.... I'm confused in this recursion..
2. I heard it's not wise to dynamically allocate memory in ctr. Why?
Can anyone please explain how this logic gets executed simply by
compiler?
Thanks in advance.
- Bharath
I was going through a c++ manual in msdn site
"http://msdn2.microsoft.com/en-us/library/kewsb8ba.aspx". There there
was a small note on usage of new operator :
"When new is used to allocate memory for a C++ class object, the
object's constructor is called after the memory is allocated."
So, I got a doubt and quickly executed below program. Its o/p is : base
#include <iostream.h>
#include <stdlib.h>
class base
{
int *p;
public:
base()
{
p=new int[1000];
std::cout<<"base";
}
};
int main()
{
base *bptr=new base;
delete bptr;
system("PAUSE");
return 0;
}
My doubt here is on "base *bptr=new base;" statement.
1. if iam right, to create an object here compiler uses ctr "base()".
So, ctr gets executed once. Since I used new here as per msdn manual
statement constructor should be called again & "base" should be printed
again.... I'm confused in this recursion..
2. I heard it's not wise to dynamically allocate memory in ctr. Why?
Can anyone please explain how this logic gets executed simply by
compiler?
Thanks in advance.
- Bharath