I'm no C++ expect, as you will undoubtedly notice. But I'm trying to "upgrade" some old C code to C++. In the process, I'm trying to promote old structures to classes. I found this Oracle article about some of the things I'm trying to do.
http://www.oracle.com/technetwork/articles/servers-storage-dev/mixingcandcpluspluscode-305840.html
But 2 things. The article doesn't address a more complicated case I have. And my "workaround" doesn't seem to lead consistent results. So here I go with some details.
Old C-Style structure:
typedef struct
{
int ia;
float fa;
...
} Struct_A;
typedef struct
{
Struct_A sA;
int ib;
float fb;
...
} Struct_B;
C++
According to the Oracle article, I should be able to promote Struct_A to a class and still be able to use the class version with old C functions. Here's apparently how:
class CStruct_A : public Struct_A // Inherits from C- Struct_A
{
public:
CStruct_A() : ia(0), fa(0.0f) {}
}
Pause. Right here, I already have an issue. I can't seem to initialize the C-Structure elements as indicated in the article and as shown above. The compiler doesn't accept it. I have to re-write the class as:
class CStruct_A : public Struct_A
{
public:
CStruct_A()
{
ia = 0;
fa = 0.0f;
}
}
So that's the first question mark. Not a huge deal but the article claims it can be done.
Next, the tougher issue. Promoting the Struct_B, which contains a Struct_A member. I want to make sure Class A's constructor is used to initialize the variables. But I'm not sure how to force it. In my c++ code, if I have something like:
{
CStruct_B *pCStrb = new CStruct_B();
...
}
Class B's constructor gets invoked but not class A's. The workaround I have is lame... But that's the only thing I can figure out for now. I declare an internal private function ini() in class A, make class B a friend and call init() from class B's constructor.
class CStruct_A : public Struct_A
{
friend class CStruct_B;
public:
CStruct_A() { init(); }
private:
void init()
{
ia = 0;
fa = 0.0f;
}
}
class CStruct_B : public Struct_B
{
public:
CStruct_B()
{
ib = 0;
fb = 0.0f;
static_cast<CStruct_A *>(&sA)->init();
}
}
I have more questions but this is probably already too long.
Any help will be greatly appreciated.