0

I have a class that looks as follow:

#include <string>
using std::string;

class cOb
{
private:
    string var1;
    int    var2;
    int    var3;

public:
    cOb(string v1, int v2, int v3);
};

cOb::cOb(string v1, int v2, int v3)
{
    var1 = v1;
    var2 = v2;
    var3 = v3;
}

int main()
{
    string x = "Somethin";
    int y = 0, z = 10;
    cOb object1(x,y,z);
}

but if I try to create an array of objects of this class as:

cOb aObjects[10]("" ,0 ,0 );

The compiler complains and give me this error:

error: bad array initializer

How can I create a default value so I don't have to initialize every object or how do I initialize this array in the correct way?

1
  • I was trying to be brief >_> Commented Oct 30, 2014 at 21:35

2 Answers 2

2

You can write:

cOb Objects[10] = { cOb("x", 0, 0), cOb("y", 1, 1),  /* etc. */  };

It's not possible to specify a single default which is used to initialize all of the objects. To do that you'd have to give a default constructor to cOb. The simplest way to do this is to give default values to the arguments for your existing constructor:

cOb (string v1 = "", int v2 = 0, int v3 = 0 );

However if you use std::vector as your container, instead of a C-style array, you can pass a default:

std::vector<cOb> Objects( 10, cOb("x", 0, 0) );
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot initialize an array of objects that way. You can make a default constructor with no arguments, which initializes the member to default values. Or, if you're using C++11, you can use in-class member initialization:

int var2 = 0;
int var3 = 0;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.