473,320 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Query on new operator for object construction

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

Sep 3 '06 #1
2 2366
bh**************@gmail.com wrote:
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....
No, why?
I'm confused in this recursion..
Obviously.

Your new in the constructor isn't allocating memory for the base
objects, but for the 1000 ints. Therefore, the base constructor is
only called once.
>
2. I heard it's not wise to dynamically allocate memory in ctr. Why?
If something else in the constructor would throw an exception, you
would leak the allocated memory.

In your case, it will leak anyway, as you don't have a destructor with
a delete[] p. That's another danger. :-)
>
Can anyone please explain how this logic gets executed simply by
compiler?
It is just compiler magic. The language doesn't say how it is to be
done.
Bo Persson
Sep 3 '06 #2

bh**************@gmail.com wrote:
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
< clipped outdated code >
>
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..
First off, the statement base* ptr is a pointer, not an object.
Pointers do nothing else except hold a valid or invalid address of some
predefined type. Declaring a pointer invokes no object constructors.

In the code above, the new keyword invokes a single default base ctor.
The text at msdn is in fact wrong, because its typical for a ctor to
use an init list. Now consider what happens when a new allocation DOES
throw an exception, change the new allocation below to some
rediculously huge value.

// proj_exception
#include <iostream>
#include <stdexcept>

class base
{
int* p;
public:
base() : p( new int[1000] )
{
std::cout << "base()\n";
}
~base()
{
delete [] p;
std::cout << "~base()\n";
}
};

int main()
{
try
{
base* ptr = new base;
delete ptr;
}
catch ( const std::exception& r_e )
{
std::cout << "Error: " << r_e.what();
std::cout << std::endl;
}
return 0;
}
>
2. I heard it's not wise to dynamically allocate memory in ctr. Why?
Says who? When a programmer uses new, he is basicly telling the
compiler that "i'm taking over the reponsability of allocation and
deallocation". Don't expect MS to understand that statement.
If the integer allocation fails, an exception will be thrown and the
base constructor will never complete execution. So nothing needs to be
destoyed but that exception should be handled by something somewhere.

The point here is that C++ prefers that the responsability of
allocation and deallocation be well defined. Distributing allocation
overthere and distributing deallocation over here is not a good idea.
Whats needed is a way to handle allocations a smarter way: thats where
smart pointers are handy.
http://www.parashift.com/c++-faq-lite/exceptions.html

Don't loose sight of the big picture. It would be so much more usefull
to create that base class like so:

// proj_exception
#include <iostream>
#include <vector>
#include <stdexcept>

class base
{
std::vector< int vn;
public:
base() : vn()
{
std::cout << "base()\n";
}
base(int n) : vn(n, 0)
{
std::cout << "base(int n) ";
std::cout << "vn's size = " << vn.size();
std::cout << "\n";
}
~base()
{
std::cout << "~base()\n";
}
};

// look ma! no pointers...
int main()
{
try
{
base a;
base b(1000);
}
catch ( const std::exception& r_e )
{
std::cout << "Error: " << r_e.what();
std::cout << std::endl;
}
return 0;
}

/*
base(int n) vn's size = 1000
~base()
*/

Sep 4 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
by: Ioannis Vranos | last post by:
When we use the standard placement new operator provided in <new>, and not a definition of owr own, isn't a call to placement delete enough? Consider the code: #include <new>
6
by: Jerry Krinock | last post by:
I'm writing a class which has, as members, dynamically allocated valarrays. I'd like to overload the "=" operator so that, when operating on two objects of my class, the valarray values of the rhs...
0
by: Robert Potthast | last post by:
Hello, I want to make my garbage collector more safe. To make it more safe I need to know if an object has been allocated on the stack or on the heap using the operator new. My garbage collector...
3
by: Martin Vorbrodt | last post by:
In "C++ Templates, The Complete Guide" i read that template copy-con is never default copy constructor, and template assignment-op is never a copy assignment operator. Could someone please explain...
8
by: David Williams | last post by:
Hi all, I have a templated Vector3D class which holds (x,y,z) components as the specified type. I quite often wish to cast a Vector3D holding ints into a Vector3D holding floats and vice versa....
19
by: scroopy | last post by:
Is it impossible in C++ to create an assignment operator for classes with const data? I want to do something like this class MyClass { const int m_iValue; public: MyClass(int...
13
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help...
3
by: dizzy | last post by:
Hi I wonder if this code is standard conformant and should work on all conformant implementations (for some type T): 1: void* mem = ::operator new(sizeof(T)); 2: T* p = new(mem) T(args...);...
3
by: C++Liliput | last post by:
Hi, I was looking at the implementation of operator new and operator new in gcc source code and found that the implementation is exactly the same. The only difference is that the size_t argument...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.