Writing the Constructor for the Array for Objects

  • Thread starter Thread starter sameergk
  • Start date Start date
  • Tags Tags
    Array Writing
AI Thread Summary
The discussion revolves around the challenges of initializing an array of objects in C++ using a constructor that requires parameters. The original poster encounters a compiler error when trying to create an array of class A objects, as the default constructor is not sufficient for initialization with dynamic values. Participants suggest various solutions, including initializing the array after instantiation, using an array of pointers with the `new` operator, or utilizing STL containers like `std::vector` for easier management. One participant highlights that C++ does not automatically instantiate individual objects like Java does, leading to the necessity of manual initialization. Alternatives discussed include using a static counter for object initialization, but concerns are raised about the complexity and overhead of this method. The conversation emphasizes the importance of understanding memory management in C++ and the potential pitfalls of mixing memory allocation methods. Overall, the thread provides insights into object initialization techniques in C++, addressing both practical solutions and theoretical considerations.
sameergk
Messages
4
Reaction score
0
consider the program
Class A
{
int a;
public:
A(int m = 0)
{
a = m;
}
}

int main()
{
int i = 0;
/* Intansiate/Initilize Object with the Constructor */
A Object(0);
/* Here is the Problem */
/* Create the 32 Objects of Class A */
A nObjects[32]; /* ... How to instantiate here for the array of objects?? */
}

Now if i want to initialize the nObjects.a = i during the constructor call;
How do i achieve that?
Here i get a compiler error stating no constructor match found for nObjects.
 
Technology news on Phys.org
sameergk said:
consider the program
Class A
{
int a;
public:
A(int m = 0)
{
a = m;
}
}

int main()
{
int i = 0;
/* Intansiate/Initilize Object with the Constructor */
A Object(0);
/* Here is the Problem */
/* Create the 32 Objects of Class A */
A nObjects[32]; /* ... How to instantiate here for the array of objects?? */
}

Now if i want to initialize the nObjects.a = i during the constructor call;
How do i achieve that?
Here i get a compiler error stating no constructor match found for nObjects.


Well that's interesting. I dont' think you can. When the compiler creates the array of 32 A items, it calls the constructor 32 times. Pretty sure anyway. Don't think you can link into this calling phase and pass dynamic data to the constructor while that's being done. Can always just initialize it after the array is instantiated. Not as elegant I know. Could be wrong though. I'd bet only a dollar I'm right.
 
You could do something like this:

A nObjects[32] = {1,2,3,4,5,6,7,8,...,32};
 
dduardo said:
You could do something like this:

A nObjects[32] = {1,2,3,4,5,6,7,8,...,32};

Thanks. :blushing:
 
dduardo i always forget that method could you...for large parameter list
like constr(char*,int) do you just do

={ "",1, "",2,"",3 ...};
 
Dduardo . . . I knew it just as good as you at one time. Suppose that don't help me now though. And I really like using a debugger. That's especially nice with C++ so you can see all the calls, you know for polymorphism.

Anyway . . . good for you Dduardo. :smile:
 
Last edited:
I still don't find to have got a sufficing solution. Its really bugging me out.
For the fact that I can achieve the same in Java because of the new () for each objects, that actually instantiates the individual objects.
Here in C++ i don't thing that i have any other options, other than initializing each of the objects in a loop, after instantiating(creating) them with the constructor calls.
 
sameergk said:
I still don't find to have got a sufficing solution. Its really bugging me out.
For the fact that I can achieve the same in Java because of the new () for each objects, that actually instantiates the individual objects.
Here in C++ i don't thing that i have any other options, other than initializing each of the objects in a loop, after instantiating(creating) them with the constructor calls.
The new operator exists in C++. The difference with Java is that Java declares only references (pointers) to objects which are then created with the new operator and linked with the pointer automatically by Java. In C++ you can do the same yourself: declare an array of pointers and then create the objects with the new operator.
A* objects[ i ];
and initialize them in a for loop.
objects[ i ] = new A( value );
 
There's two solutions: either use the solution that ramollari suggests and use new, or provide a default constructor (a constructor that takes zero arguments) and provide a separate method called "initialise" or somesuch which can be called on each element of the array.

Please be careful when using new, however, especially if you are used to using Java. Any new'd memory must be deleted, and if you declare an array using new [], you must also use delete []. Failure to do this will result in a memory leak and a possible loss of system stability.

Furthermore, never mix new and free and malloc and delete.

Example:

Code:
int main()
{
    A* array = new A[32];
    for(int i = 0; i < 32; ++i)
        array[i] = new A(5);
    delete [] array;
    return 0;
}
 
  • #10
First off, I'm puzzled that your code, as written, doesn't compile, since you do give a default constructor for A.


Another option, though a little trickier, is to allocate raw memory, and instantiate your A objects directly in that memory.

E.G. something like:

Code:
unsigned char *buffer = new unsigned char[n * sizeof(A)];
A *array = (A*) buffer;

for(int i = 0; i < n; ++i) {
  // Create an object -here- without allocating
  new( (void*)(array + i) ) A(i);
}

// Do stuff

for(int i = 0; i < n; ++i) {
  // Destroy this object without deallocating
  array[i].~A();
}
delete[] buffer;

Incidentally, buffer could have been statically allocated too, instead of dynamically allocated as I did.


If you're using the STL, you should also be able to do something like this:

Code:
std::vector<int> init(32);
for(size_t i = 0; i < 32; ++i) init[i] = i;
std::vector<A> array(init.begin(), init.end());

but, of course, this only works when you just want to use a one-parameter implicit constructor. A good implementation of the STL will not use the default constructor for A when compiling the above code.
 
Last edited:
  • #11
I don't think the guy needs to worry about memory pooling just yet :biggrin:
 
  • #12
Probably not. But it's fun to know that you can do it, even if you don't intend to try to do it. :smile: And there's always the chance he genuinely needs to do something like this, and double indirection (array of pointers to objects) is too slow or fragmented for his needs.
 
  • #13
1. The Code was not compiling, since i had a constructor that takes 1 parameter, like this
A(int m )
{
a = m;
}
So as to make the code compilable,I modified the above constructor to take 1 or Zero Argumnets.

2. I'm not really intersted in explicitly initializing the objects after having created/ initilized(by Constructors).

What I really intend is to use the constructors, to intialize the objects during the time of their creation to a particular value, that can be passed as an argument to the constructor.

Since i needed the above count to work only for the Local objects that are created in some function, I had implemted the required behavior in a different fashion. As shown below

static int Loacal_Objects_Counter = 0;
Class A
{
int a;
public:
A()
{
a = Loacal_Objects_Counter ;
}
A(int m)
{
a = m ;
}

};
int func()
{
/* Store the Objects_Counter Value */
int Currnet_Counter = Local_Objects_Counter;

/* Reset the Local_Objects_Counter */
Local_Objects_Counter = 0;

/* Calling the Zero Arg Constructor :: Thus having initailized the objects during the construction as desired */
A Objects[32] ;
/* Do the Rest */
...
/* Reset the Static Counter Back to its initial value. */
Local_Objects_Counter = Currnet_Counter;
}

Though i could achieve, what i intended, i was not satisfied in using the file/class specific static variable,
And also the overhead in each of the functions, to store and restore the counter varaible.
I m in search of a better alternative.
 
  • #14
I have no idea what you are trying to do. I read your explanation, read your code and I'm still none the wiser. Why have you introduced a static variable? Why not simply use new instead of allocating your objects on the stack?
 

Similar threads

Replies
25
Views
2K
Replies
36
Views
3K
Replies
31
Views
3K
Replies
23
Views
2K
Replies
13
Views
1K
Replies
89
Views
6K
Replies
35
Views
4K
Replies
3
Views
2K
Back
Top