initilize array member's size in object constructor?

C

crichmon

Is there away to initialize an array's size through constructor
initialization?

Right now I have

///////////////
class foo
{
string bar[20];
public:
foo();
}

////
foo::foo()
{
};


////////////////

could something be done like

///////////////
class foo
{
string bar[];
public:
foo();
}

////
foo::foo(): bar[20]
{
};


////////////////

Any help?

thanks,
crichmon
 
A

Alf P. Steinbach

* crichmon:
could something be done like

///////////////
class foo
{
string bar[];
public:
foo();
}

////
foo::foo(): bar[20]
{
};

class Foo
{
private:
std::vector<std::string> bar;
public:
Foo(): bar(20) {}
};
 
R

Rolf Magnus

crichmon said:
Is there away to initialize an array's size through constructor
initialization?

Right now I have

///////////////
class foo
{
string bar[20];
public:
foo();
}

////
foo::foo()
{
};

class foo
{
string* bar;
public:
foo();
//don't forget copy construction/assignment/destructor
};

foo::foo()
: bar(new string[20])
{
}
////////////////

could something be done like

///////////////
class foo
{
string bar[];
public:
foo();
}

////
foo::foo(): bar[20]
{
};

No. Why would you want that? Note that a class has a size that is fixed
at compile time, so you couldn't put a non-constant expression between
the brackets anyway. And in the other case, you wouldn't gain anything.
 
J

John Harrison

Is there away to initialize an array's size through constructor
initialization?

Right now I have

///////////////
class foo
{
string bar[20];
public:
foo();
}

////
foo::foo()
{
};


////////////////

could something be done like

///////////////
class foo
{
string bar[];
public:
foo();
}

////
foo::foo(): bar[20]
{
};


////////////////

Any help?

thanks,
crichmon

Use a vector

class foo
{
vector<string> bar;
public:
foo();
}

////
foo::foo(): bar(20)
{
};

It's what vectors are for.

john
 
A

Alf P. Steinbach

* John Harrison:
Use a vector

class foo
{
vector<string> bar;
public:
foo();
}

Here should be a semicolon.

////
foo::foo(): bar(20)
{
};

Here should not be a semicolon.

I gather my reply to the same posting had not yet reached your
news-server.
 
F

Fraser Ross

A nontype template parameter can be used.

template <int val=20>
class foo
{
string bar[val];
};

foo<30> test();

Fraser.
 
R

Rolf Magnus

Fraser Ross said:
A nontype template parameter can be used.

template <int val=20>
class foo
{
string bar[val];
};

foo<30> test();

<Nitpick>
Note that 'test' is a declaration of a function that returns a foo<30>.
I don't think you actually wanted that.
</Nitpick>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top