[RESOLVED] Pointer to an array of pointers to a structure
Hi,
I have an abstract class like this:
Code:
class Obj
{
public:
virtual int someFunc()=0;
protected:
struct A
{
int Index;
std::string Name;
std::string Hier;
};
A **a;
};
And then I derive a class from this like this:
Code:
class derObj : public Obj
{
public:
int someFunc();
private:
struct A a[2] = {
{ 1, "name","Top" }, { NULL, NULL, NULL}
}
};
This doesn't work out however and I get error messages:
Code:
error: a brace-enclosed initializer is not allowed here before '{' token
error: ISO C++ forbids initialization of member 'a'
error: making 'a' static|
error: invalid in-class initialization of static data member of non-integral type 'Obj::A [2]'
Please can anybody help me determine what is causing this error. Any help would be appreciated. Thanks.
Re: Pointer to an array of pointers to a structure
Thanks for the reply. I need a const array that needs to be initialized in the derived class but it needs to be accessible from the function defined in the parent class. So how can I do this?
Re: Pointer to an array of pointers to a structure
The above scheme worked nicely. The problem was initializing the string variables with NULL. I initialized them with empty strings "" and then it worked fine.
Re: Pointer to an array of pointers to a structure
Originally Posted by aryajur
The above scheme worked nicely. The problem was initializing the string variables with NULL. I initialized them with empty strings "" and then it worked fine.
To explain your problem, assigning NULL to a std::string produces undefined behaviour. The string constructor does not take NULL's.
You must construct a string correctly, and assigning NULL to a string is incorrect. The reason is that NULL will be converted to a 0, and then internally the string class will call the constructor, but which constructor? No constructor of std::string has a single argument that takes an int. So the closest constructor is the one that takes a const char*. You are now initializing std::string using the const char* constructor, and that constructor requires that whatever is pointed to be terminated with a NULL. The string class may now attempt to dereference a NULL pointer when performing this operation, and doing that is undefined behaviour.
So the string should be initialized to an empty string, not NULL.
Regards,
Paul McKenzie
Last edited by Paul McKenzie; March 12th, 2011 at 08:52 PM.
Bookmarks