Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

C++ Classes with Variable Length Array Members

23 views
Skip to first unread message

Nordlöw

unread,
Oct 15, 2009, 9:09:40 AM10/15/09
to
GCC's C Extensions gives us zero and variable length arrays.

Is it possible to get variable length arrays as members ("by-value")
in C++ classes aswell, something like:

class string255
{
private:
char size;
char val[size];
}:

I guess it all boils downto how C++ allocates a class.

Can we give gcc hints about this somehow?

/Nordlöw

Robert Heller

unread,
Oct 15, 2009, 10:30:17 AM10/15/09
to

That is one of the things that what constructors and static members are
for.

You can't define a member array with another member as the size, but you
can do this:

class string255
{
private:
char size;

char *val;
char dummy;
public:
string255(int _size) {
assert(_size > 0 && _size < 256);
val = new char[_size];
size = _size;
}
~string255() {
if (val != null) delete val[];
}
char& operator [] (i) {
if (i >= 0 && i < size) return val[i];
else return dummy;
}
};

This pretty much implements what you want I believe. i suspect you will
want to add a copy constructor and an assignment operator method, but I
will leave them as a homework assignment :-). If you want something
'more automagical' there is the STL or maybe you want to use a dufferent
OO language altogether (Tcl+SNIT maybe).

>
> /Nordl=F6w
>

--
Robert Heller -- 978-544-6933
Deepwoods Software -- Download the Model Railroad System
http://www.deepsoft.com/ -- Binaries for Linux and MS-Windows
hel...@deepsoft.com -- http://www.deepsoft.com/ModelRailroadSystem/

0 new messages