473,721 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

calling constructor when allocating an array

Hello, a very simple question:
Ok I have a class MyClass with a constructor MyClass(int) (no constructor
without argument defined)

how can I make an array of pointers to objects of that class, calling the
constructor with the index number as argument?

<code>
int N = 22;
pointerArray = new MyClass*[N];
for (int i=0; i< N; i++)
pointerArray[i]->MyClass(i);
</code>

is this correct? does the second line call some default constructor for
MyClass? Any better idea how to do that?

Thanks Phil
Jul 19 '05 #1
21 17871
Sorry my code was wrong... Is this correct?

<code>

int N = 22;
pointerArray* MyClass;
pointerArray = new MyClass[N];
for (int i=0; i< N; i++)
pointerArray[i]->MyClass(i);

</code>

Jul 19 '05 #2
Philipp wrote:
Sorry my code was wrong... Is this correct?

<code>

int N = 22;
pointerArray* MyClass;
This is not a pointer array. It is a pointer to an array.
pointerArray = new MyClass[N];
new creates an array of N pieces of objects of MyClass type.
for (int i=0; i< N; i++)
pointerArray[i]->MyClass(i);


This is not good. The MyClass types are already constructed. And you
cannot call constructors, they have no name. What do you want to do?

--
Attila aka WW
Jul 19 '05 #3
Philipp wrote:
int N = 22;
pointerArray* MyClass;
You mean 'MyClass * pointerArray;'. Why not post the real code?
pointerArray = new MyClass[N];
This calls the default constructor for MyClass N times.
for (int i=0; i< N; i++)
pointerArray[i]->MyClass(i);


Should be
for (int i = 0; i < N; ++ i) pointerArray [i] = MyClass (i);
or
for (int i = 0; i < N; ++ i)
{
pointerArray [i].~MyClass ();
new (& pointerArray [i]) MyClass (i);
}

If you allocate raw memory instead of objects:
pointerArray = reinterpret_cas t <MyClass *>
(new char [N * sizeof (MyClass)]);

then you don't need the destructor call before the
placement new inside the for loop. However, in that
case you would need:

for (int i = 0; i < N; ++ i) pointerArray [i].~MyClass ();
delete [] reinterpret_cas t <char *> (pointerArray);

instead of just 'delete [] pointerArray;'.

Basically, the point is that you can't call a constructor on an
object (because by the time it is an object, it has already been
constructed).

I hope this helps, and that I haven't made too many mistakes of my own.
Regards,
Buster.

Jul 19 '05 #4
Attila Feher wrote:
int N = 22;
pointerArra y* MyClass;


This is not a pointer array. It is a pointer to an array.


No, it's a syntax error. A pointer to an object would look like this:
MyClass * pointerArray;

A pointer to an array would look like this:
MyClass (* pointerArray) [NN];
// NN is a (compile-time) integral constant

Regards,
Buster.

Jul 19 '05 #5

"Philipp" <_N************ ******@hotmail. com> wrote in message
news:3f******** @epflnews.epfl. ch...
Sorry my code was wrong... Is this correct?

<code>

int N = 22;
pointerArray* MyClass;
pointerArray = new MyClass[N];
for (int i=0; i< N; i++)
pointerArray[i]->MyClass(i);

</code>


No. It would be much easier if you had a default constructor. Then you
could just declare an array of objects instead of pointers. But to create
an array of pointers, you first need to declare the array, then create
instances of the objects for each array item to point to. You can't just
call a constructor like a function...you have to "new" each pointer, like
this:

int N = 22;
pointerArray* MyClass[N]; // no need to "new" this!
for (int i = 0; i < N; ++i)
pointerArray[i] = new MyClass(i); // create each instance!

....and, later, to delete...

for (int i = (N-1); i >= 0; --i)
delete pointerArray[i]; // delete each instance

(BTW, you could count upwards in the delete loop, I just got in the practice
long ago of deleting in the opposite order I allocated in, because on some
systems it prevented memory fragmentation.. .but that's just me.)

-Howard

Jul 19 '05 #6

"Philipp" <_N************ ******@hotmail. com> wrote in message news:3f******** @epflnews.epfl. ch...
int N = 22;
pointerArray* MyClass;
pointerArray = new MyClass[N];
for (int i=0; i< N; i++)
pointerArray[i]->MyClass(i);


You can NOT call constructors at all. They are called for you as part
of normal object creation. You can't create an array with other that
default initialization. A vector, which is probably better suited for what
you want to do anyhow, can be initialized with a non-default object, but
it is the same for all elements.

Besides, you're not initializing the array in the C++ sense. Initialization
via the default constructor occurs when the new is invoked. But you
can do what you are trying to do if you just put allt he stuff that would have
been in your MyClass(int) constructor in a regular member function.

Your class would look like:
class MyClass {
public:
MyClass(); // default constructor required
MyClass(int i) { Init(i); }

void Init(int i);
};

vector<MyClass> pointerArray(N) ;
for(int i = 0; i < N; ++i) pointerArray[i].Init(i);

Now you don't even have to worry about deleting the array.
Jul 19 '05 #7

"Howard" <al*****@hotmai l.com> wrote in message
news:bk******** @dispatch.conce ntric.net...

pointerArray* MyClass[N]; // no need to "new" this!

DOH! Now he's goe ME doing it! :-) That should be (of course)

MyClass* pointerArray[22];

-Howard
Jul 19 '05 #8
On Wed, 17 Sep 2003 16:02:05 +0200
"Philipp" <_N************ ******@hotmail. com> wrote:
Sorry my code was wrong... Is this correct?

<code>

int N = 22;
pointerArray* MyClass;
pointerArray = new MyClass[N];
for (int i=0; i< N; i++)
pointerArray[i]->MyClass(i);

</code>


i think you're trying to do something like this:

int N = 22;
// the ** makes the array of pointer not array of objects
MyClass **pointerArray;

// crerate all the Pointer
pointerArray = new (MyClass*)[N];

// create all the objects
for (int i=0; i< N; i++)
pointerArray[i] = new MyClass(i);
regards
Clemens
Jul 19 '05 #9
OK that helped a lot. Thank you (I'm still a bit confused about arrays and
pointers... hmmm, newbie perhaps? :-)
Jul 19 '05 #10

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

Similar topics

5
1683
by: Sylvain | last post by:
Let's say I have the following code where a class 'pipo' has 8 instances of foo: class foo { foo ( const char * _name): name = _name { }
26
2550
by: Peter Olcott | last post by:
// // Is there something wrong with my syntax for the // Copy Constructor of an Array Element, or does // the C++ language not support this? // #include <stdio.h> #include <stdlib.h> class X {
4
4963
by: Michael | last post by:
Hello, I want to use an object (LowCut) within another object (SampleRateConverter) like it is written as follows: class SampleRateConverter { public: SampleRateConverter( int iSourceSampleRate, int iTargetSampleRate ) {
5
1672
by: cpluszen | last post by:
Hi, I have developped a c++ class and I have used it in different programs without problems. Now, I'm modifying a c++ file developped by another person (it is a code example about how using a library) and I'd like to include in this code my class functionality. I get an error during execution: #include "MyClass.h";
6
5183
by: Francois Grieu | last post by:
Hello, I'm asking myself all kind of questions on allocating an array of struct with proper alignment. Is the following code oorrect ? I'm most interested by the statement t = malloc(n*sizeof(r)) and (to a degree) by the surrounding error checking.
0
8837
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
9366
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9059
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
8005
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6668
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4751
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3187
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
2572
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2129
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.