Initialize Constructor when its an array

Hi all,

How do you initialize a class constructor when its an array?

I'm struggling with the stuff in bold.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class PhoneCall{
private:
    string number;
    float rate;
    int length;
public:
    PhoneCall();
    PhoneCall(string initNumber , int initLength , float initRate);
};

int main(){
   PhoneCall phoneCallDirectory[100];
   
   int count = 0;
   for(int i = 0; i < 100;i++){
     phoneCallDirectory[count]->PhoneCall("" , 0 , 0);
     count++;
   }
}


Thanks,

Stephen
What seems to be the problem?
With an array the elements are initialized using the default constructor. So you can't use arguments.
So are you saying the only way to fix the problem is to use property accessors
Last edited on
Yes.
Well, for your example you can simply define a default constructor:
1
2
3
4
5
PhoneCall::PhoneCall()
: rate(0.0f)
, length(0)
{
}


That constructor will be called for every element of the array when you create it.
It might be possible. See http://www.cplusplus.com/reference/std/new/operator%20new/. The third form allows the selection of the constructor. In the example, see lines 18 to 25.

But so we are clear: Your current approach of an array in the stack does not allow the selection of the constructor. The previous answers are truly correct. I am saying: Instead of an array in the stack, dynamically create one in the heap and construct the objects with operator new.
Last edited on
Instead of trying to emulate a vector, just use it http://www.cplusplus.com/reference/stl/vector/

However phoneCallDirectory[count]->PhoneCall("" , 0 , 0); what do you want to do there?
phoneCallDirectory[count] is an object, you access its fields with the dot operator.
If you want to set it to that value, maybe it is a work for the default constructor
Or phoneCallDirectory[count] = PhoneCall("" , 0 , 0);
+1 to the vector, but note that this is not exactly the same, or maybe I don't know how to use the vector.

The vector will use the copy constructor and the user wants to use some other constructor. If I dynamically create the vector myself, my performance will be better than if I used vector, right?
I thought that the copy constructor could be bypassed. I mean if the object will be destroyed next, something like RVO could be used.
http://en.wikipedia.org/wiki/Return_value_optimization

There is also the alternative of storing pointers instead (but that is awful).

Other than that I don't know how you could avoid the copy constructor.
I think the copy ctor is not bypassed in vector<>. :-( I recently read a PPT about custom allocators for use with STL containers and apparently all containers push the item using the copy constructor. The memory allocator objects even have a construct() method that uses the placement new operator to place the copy in the allocated memory.
Topic archived. No new replies allowed.