3

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!

3
  • Are you using the latest C++ x11 standards? Commented Dec 11, 2014 at 22:37
  • @George_Houpis yes, but if there are different versions to solve the problem, please post both of them Commented Dec 11, 2014 at 22:38
  • related Commented Dec 11, 2014 at 22:39

2 Answers 2

3

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().

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the fast replay, but is there a more convenient way (in case there are 20+ objects to create)?
@DonMan another option is to use std::vector.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.