473,804 Members | 4,181 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<<"bas e";
}
};
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 2393
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<<"bas e";
}
};
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
4158
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
1407
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 will be assigned to the valarray values of the lhs. Well, in doing so I have discovered something I don't understand about this operator; it destroys my operands upon return. I've written the following demo, simplified to use ints instead of...
0
1649
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 uses a mixture of reference counting and smart pointers. I have got a base class ("Object") which handles all the memory management stuff. I have worked out different approaches to pass the info to my base class (won't name all):
3
10281
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 how I could declate/override the two. Thanx
8
9185
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. Like so: Vector3D<int> intVec(10,20,30); Vector3D<float> floatVec = intVec; Of course this doesn't work. I would be happy if instead the following
19
2237
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 iVal):m_iValue(iVal){}
13
3980
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 is much appreciated. JD
3
1777
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: delete p; line 2 I know it should be fine because global operator new should return
3
3522
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 passed to the operators is calculated correctly during runtime and passed in. Inside the implementation both operators (new and new) do a simple malloc(). Ditto for operator delete/delete. I have two questions: 1) Who passes in the size_t argument...
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10076
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3816
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.