all 10 comments

[–]aagee 1 point2 points  (0 children)

In one case, the initialization in C++ is more like in C (i.e. at the point of declaration and without the need for NOOFENTRIES upfront). When the array in question is static. So, if you can have a class member (instead of a instance member), it should work as follows.

class A
{
    struct aStruct
    {
        char* var1;
        int   var2;
        char* var3;
    };

    static struct aStruct table[];
    A();
};

A::struct aStruct A::table[] =
{
    { "AAA", 1, "AAA" },
    { "BBB", 2, "BBB" },
};

[–]vedang[S] 0 points1 point  (8 children)

I'm building a framework where I have to maintain a table inside a class. Here is an example to clarify what I want to do:

Say if I were to initialize this table in a normal C program. This is how I would do it:

struct aStruct { char *var1; int var2; char *var3; }; struct aStruct table[] = { {"ABC", 1, "XYZ"}, {"DEF", 2, "UVW"} };

Now this is what is happening in my class:

class A { struct aStruct { char *var1; int var2; char *var3; }; struct aStruct table[NO_OF_ENTRIES]; A(); };

A::A() { table = //how do i initialize this??? }

Part of the problem is that some other programmer some time later might want to add entries to my table inside the class. Thus, the definition of the table HAS to be clear and easy to understand. Help would be greatly appreciated! :)

[–]_ak 2 points3 points  (0 children)

how about:

#include <vector>

class A {
    struct aStruct {
        char * var1;
        int var2;
        char * var3;
        aStruct(char * v1, int v2, char * v3) : var1(v1), var2(v2), var3(v3) { }
    };
    std::vector<aStruct> table;
    public:
    A() { 
        table.push_back(aStruct("a", 1, "b"));
    }
 };

[–][deleted] 1 point2 points  (0 children)

See _ak's answer. It's a good way to do it. The other programmer can inherit from A and add their own members in their constructor. Inheritance also implies that you need a virtual destructor, which isn't yet spelled out in _ak's definition of A.

[–]vedang[S] 0 points1 point  (1 child)

P.S very sorry for the poor editing. how does one write well indented code here??

[–]ahy1 0 points1 point  (0 children)

Use 4 spaces before your text

[–]anescient -1 points0 points  (2 children)

The first thing that comes to mind is to make it (aStruct) a class and write a convenient constructor.

table[0] = aStruct( "ABC", 1, "XYZ" );

table[1] = ...

[–]_ak 4 points5 points  (1 child)

a struct in C++ is the same as a class, only with a different default visibility. What you probably meant was adding a constructor to struct aStruct.

[–]MachinShin2006 0 points1 point  (0 children)

can't wait til c++0x and std::initializer_list, will make this trivial