Calling a constructor in a loop

I have a constructor which take 3 arguments including 3 vector of vector of type double and one vector of pointers double. Let's say the loop iterate 4 times, if I call the constructor with result of each iteration but not within the loop it works fine,but when I call the constructor in a loop it work correctly just for the first iteration. Based on what I see here I think the constructor is created just to be called once in a life time. Now my question is how I can call a constructor in a loop when the constructor's input variables change over the time?I would be really grateful if you could help me with one example.
Last edited on
Please show your code!

A constructor is called when a new object is created. So it is not possible to call the constructor more than once - at least not on the same object instance. Each constructor invocation creates a new separate object.

Do you want to create a new separate object in each iteration of the loop? If so, calling the constructor is possible, but you'll have to be aware that you are going to create n distinct objects, one for each iteration. Otherwise, if you do not want to create a new separate object in each iteration of the loop, but instead want to "update" the existing object instance, then you obviously can not use the constructor for that purpose!

1
2
3
4
5
for (int i = 0; i < 42; ++i)
{
    MyClass instance(i); // <-- constructs a new object instance, on the stack, in each iteration
                         // this object will be *destroyed* when it goes out of scope at the end of the current iteration!
}


1
2
3
4
5
6
std::vector<MyClass*> object_list; // <-- we'll store pointers to the object instances in this std::vector
for (int i = 0; i < 42; ++i)
{
    MyClass *instance = new MyClass(i); // <-- constructs a new object instance, on the heap space, in each iteration
    object_list.push_back(instance);    // <-- store the pointer to the current instance, so that it can be accessed/destroyed later
}


1
2
3
4
5
MyClass instance(); // <-- constructs just a single object instance
for (int i = 0; i < 42; ++i)
{
    instance.do_something(i); // <-- do something with the existing (single) instance
}
Last edited on
Thanks for your answer. I apologize for not posting any code. I will try to make an example and post the code here. Is that possible to make the instances like instance=new instance or something like this using "new" keyboard?
Last edited on
Well, I think the three example above are the options that you can choose from...
Last edited on
instance=new instance is not syntactically correct. kigar64551 gave you the correct syntax for using new in his second example (line 4). Don't forget that for every call to new, there must be a corresponding call to delete or you will have a memory leak.
what I'm doing wrong here? It can't pass the line where Init member function is called. In this case my class doesn't have a constructor. It just have some member function.

1
2
3
4
5
6
7
8
9
10
11
12
13
	std::vector<Myclass*> object_list; 
	int num_instance = T_ / dt_;
	for (int i = 0; i < num_instance; ++i)
	{
		Myclass* Myobject_ = new Myclass[i]; 
		object_list.push_back(Myobject_); 
	}

	int ins = 0;
	while (t < T_) {
		object_list[ins]->Init(&dummy1_, &dummy2_, dummy3_);
                 ins ++;
         }
Last edited on
You need to show all the code. It sounds like something is going wrong at line 11, but without seeing class Myclass, how can we know? Also we need to see the declarations of dummy1_, dummp2_, and dummy3_.
Myclass* Myobject_ = new Myclass[i];
You are creating an array of i elements, in each iteration. First iteration creates an empty (zero size) array. Second iteration creates an array of size one. Third iteration creates an array of size two. And so on...

Is that what you intended?

If you want to create just one object, per iteration, and pass i as an argument to the constructor, then use:
Myclass* Myobject_ = new Myclass(i);

...or, if the constructor (e.g. default constructor) doesn't need any argument, then just:
Myclass* Myobject_ = new Myclass();
Last edited on
you can see the same problem when calling member function in this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <vector>
#include <cstdlib>


class Test {

public:

    std::vector<double> dummy1;
    std::vector<double> dummy2;
    Test() = default;
    void Init() {

        for (int i = 0; i < 10; i++) {

          double aux= (double)rand() / RAND_MAX;
          dummy1.push_back(aux);
          aux *= 2;
          dummy1.push_back(aux);

        }

    }

};



int main()
{
    std::vector<double> dummy1;
    std::vector<double> dummy2;
    std::vector<Test*> object_list;
    for (int i = 0; i < 10; ++i)
    {
        Test* instance = new Test[i]; 
        object_list.push_back(instance);  
    }
    int iter = 0;
    while (iter < 10) {

        object_list[iter]->Init();
        dummy1 = object_list[iter]->dummy1;
        dummy2 = object_list[iter]->dummy2;
        iter++;
    }

    for (int i = 0; i < object_list.size(); i++)
    {
        delete (object_list[i]);
    }
    object_list.clear();
}


Last edited on
As mentioned above already, the following code:
1
2
3
4
for (int i = 0; i < 10; ++i)
{
    Test* instance = new Test[i];
    object_list.push_back(instance);

...will result in object_list[0] pointing to an empty (zero size) array.

Therefore, it is no surprise that object_list[iter]->Init() with iter=0 will result in undefined behavior.

You probably want to apply one of the fixes suggest above...
Last edited on
Your Test has only the default constructor, which does not take any arguments. One would create such object with new Test -- the new Test(42) is not possible.

However, why do you use new at all?

std::vector<Test> object_list( 10 ); does create a vector that has ten Test elements.

If you insist a loop:
1
2
3
4
5
for (int i = 0; i < num_instance; ++i)
{
    Test dummy;
    object_list.push_back( dummy ); 
}
Last edited on
I'm not sure what you're trying to achieve -perhaps some more detail as to what is required?

However, consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <ctime>

constexpr size_t noElems {10};

struct Test {
    std::vector<double> dummy1;
    std::vector<double> dummy2;

    Test() = default;

    void Init() {
        for (size_t i {}; i < noElems; ++i) {
            const auto aux {static_cast<double>(rand())};

            dummy1.push_back(aux);
            dummy2.push_back(aux * 2);
        }
    }
};

int main() {
    srand(static_cast<unsigned>(time(nullptr)));

    std::vector<double> dummy1;
    std::vector<double> dummy2;
    std::vector<Test*> object_list;

    for (size_t i {}; i < noElems; ++i)
        object_list.push_back(new Test);

    for (size_t iter {}; iter < noElems; ++iter) {
        object_list[iter]->Init();
        dummy1 = object_list[iter]->dummy1;
        dummy2 = object_list[iter]->dummy2;
    }

    for (size_t i {}; i < object_list.size(); ++i)
        delete (object_list[i]);

    for (const auto& d1 : dummy1)
        std::cout << std::setw(7) << d1;

    std::cout << '\n';

    for (const auto& d2 : dummy2)
        std::cout << std::setw(7) << d2;

    std::cout << '\n';
}



   7285  13702  26007  28291  10133  25421   5130  19476   9056  17581
  14570  27404  52014  56582  20266  50842  10260  38952  18112  35162

Thank you all for your answers. I tried all solutions you suggested, but still it does not update the instance variables.
Which variables? Please show a compilable example program.
I fixed it. The problem was an & missing somewhere in the code. Thank you all.
Last edited on
Topic archived. No new replies allowed.