PDA

View Full Version : A question regarding C++



mnguyen
23rd September 2004, 07:10 PM
Assume that we have a class like this :

class A
{
public:
A();

private:
int secret;
};


I want to create an array of instances of class A


A* arrA = new A[5];

This works fine.

Another situation with class B

class B
{
public:
B(int v);

private:
int secret;
};


I want to create an array of instances of class B. But how can we pass the constructor parameter in the new operator ???

B* arrB = new B[5]; <----- error, how to pass the parameters in this situation



Anyone give me an answer ?

tashirosgt
23rd September 2004, 08:31 PM
I tried a simple example and the syntax
B* arrB = new B[5](3);
works to pass the parameter 3 .
I don't know it this is supposed to work in C++, but g++ accepts it.

PompeyBlue
24th September 2004, 09:09 AM
I remember asking this exact same question when I started learning C++.

The short answer is, you can't do it. You can't create an array of classes each with their own constructor.

However, just from my own experience, C++ is awful for allowing you to do things behind your back. Constructors, when not explicity called, can mean other programmers are making incorrect assumptions as to what happens when you instance a class. IMHO it's good practice to explicitly delcare a "Construct" member which you use instead of a constructor. I.e.

A * lpMyNewClass = new A;

lpMyNewClass->Consutrct();

Any programmer who looks at your code is aware there is a constructor there and that some sort of action is taking place. Maybe they should check it out, maybe constructing a class is an expensive hobby they should not be doing in real time, maybe it's allocating vast quantities of memory, either way, it's just letting others know your class is doing some processing. However, something like:

A * lpMyNewClass = new A;

Doesn't, but I guess in your case

A * lpMyNewClasses[5] = new A[5](3);

Warns others, but as you've found, you can't call each class with a seperate constructor.

mnguyen
24th September 2004, 07:36 PM
Hi guys,

I checked the book of Bjarne Stroustrup, it said that this can be done for ONLY DEFAULT CONSTRUCTOR. The class B did not have a default constructor, so there is no way to create an array of B.

Anyway, ur opinions give me more details of C++ aspects. Really appreciate that. :D

Tks a lot guys. :)

tashirosgt
25th September 2004, 01:36 AM
According to the C++ FAQ lite at
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.5
one may do this:

class Fred {
public:
Fred(int i, int j);
...assume there is no default constructor in class Fred...
};

int main()
{
Fred a[10] = {
Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7),
Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7), Fred(5,7)
};

// The 10 Fred objects in array a will be initialized with Fred(5,7).
...
}