flaming.codes
flaming.codes

Reputation: 119

C++: Objects created via array, but how to pass parameters?

It would be great if you could help me here: I create objects as an array

Class object[3];

but I don't know how to pass parameters by creating objects this way. If only one object would be created, the code would look like this:

Class object("Text", val);

The rest is managed by the constructor. Thanks in advance for your ideas!

Upvotes: 3

Views: 1081

Answers (2)

Joel Brun
Joel Brun

Reputation: 1

you variable object is not an instance of Class but an array.
so you could use an array initialization, please look the sample below :

#include "stdafx.h"
using namespace std;

class Class {
public:
    std::string val2;
    int val2;
    Class(std::string val1, int param2){
        val1 = param1;
        val2 = param2;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    int a[3] = {1, 2, 3};
    for(int i=0; i<3; i++){
        printf("%i\n", a[i]);
    }

    Class object[3] = {Class("Text1",10), Class("Text2",20), Class("Text3",30)};

    for(int i=0; i<3; i++){
        printf("%s %i\n", object[i].val1, object[i].val2);
    }

    return 0;
}

Upvotes: 0

Anton Savin
Anton Savin

Reputation: 41301

In C++98:

Class object[3] = {Class("Text1", val1), Class("Text2", val2), Class("Text3", val3)};

But this requires Class to be copy-constructible.

In C++11 it's a bit simpler and, more importantly, doesn't require Class to be copy-constructible:

Class object[3] = {{"Text1", val1}, {"Text2", val2}, {"Text3", val3}};

If you have more than a few objects, it's better to use std::vector and push_back() / emplace_back().

Upvotes: 3

Related Questions