Writing the Constructor for the Array for Objects

In summary: A(value); delete [] array; }Thanks for the help. I think I'll go with the second solution.In summary, you could initialize the array of A objects with a constructor call, or you could allocate raw memory and instantiate the objects in that memory.
  • #1
sameergk
4
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
  • #2
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.
 
  • #3
You could do something like this:

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

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

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

={ "",1, "",2,"",3 ...};
 
  • #6
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:
  • #7
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.
 
  • #8
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 );
 
  • #9
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?
 

1. What is a constructor for an array of objects?

A constructor for an array of objects is a function that is used to create multiple objects with similar properties and methods. It allows for efficient and organized creation of objects within an array.

2. What is the purpose of writing a constructor for an array of objects?

The purpose of writing a constructor for an array of objects is to easily create multiple objects with similar properties and methods, reducing the need for repetitive code and increasing efficiency and organization.

3. How do you write a constructor for an array of objects?

To write a constructor for an array of objects, you first need to define a constructor function that contains the properties and methods you want your objects to have. Then, you can use the "new" keyword to create new objects and store them in an array using the constructor function.

4. Can a constructor for an array of objects have parameters?

Yes, a constructor for an array of objects can have parameters. These parameters can be used to set the initial values of the properties of the objects being created.

5. Can a constructor for an array of objects be used for different types of objects?

Yes, a constructor for an array of objects can be used to create different types of objects. You can define different constructor functions for different types of objects and use them to create objects with different properties and methods.

Similar threads

  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
2
Replies
36
Views
2K
  • Programming and Computer Science
2
Replies
36
Views
3K
  • Programming and Computer Science
Replies
31
Views
2K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
Replies
23
Views
2K
  • Programming and Computer Science
Replies
13
Views
878
  • Programming and Computer Science
2
Replies
35
Views
2K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
Replies
3
Views
1K
Back
Top