Reputation: 3391
Suppose we have the following structure defined:
struct MyStrusture{
unsigned char code;
unsigned char * data;
int size;
};
Is that possible to define a new struct which inherits from MyStructure and set its members at the same time? Something like this:
struct MyStrusture1 : MyStrusture{
code=1;
data={1,2,3};
size=3;
};
I have tried it but it does not get compiled I have to redefine each member in child structure. How could I reach parent members in the derived structure??
By the way, My opinion is to use MyStrusture as a function parameter so I could write the signature in this form method1(MyStructure)
when I call the function I can use MyStructure1 or 2 or etc. Is this a standard way or I should use another technique?
Thanks for any help.
Upvotes: 1
Views: 4673
Reputation: 42858
Yes, you can do it using a constructor:
struct MyStrusture{
unsigned char code;
unsigned char * data;
int size;
};
struct MyStrusture1 : MyStrusture{
MyStrusture1(); // the constructor
};
Then define the MyStrusture1()
constructor in a .cpp file, and initialize the data members there:
MyStrusture1::MyStrusture1()
: MyStrusture { 1, new unsigned char[3] { 1, 2, 3 }, 3 }
{
}
Upvotes: 0
Reputation: 27538
I assume your question is only about C++, not C, because you derive from your base structure. I'll also assume C++11.
In order to get what you want, you can use the following syntax:
struct MyStrusture1 : MyStrusture
{
MyStrusture1() : MyStrusture({ 1, nullptr, 3 }) {}
};
Note that I initialized your data
pointer to nullptr
to explain the base concept.
Initializing it with some contents the way you want to, now that's trickier. A naive approach would be:
struct MyStrusture1 : MyStrusture
{
MyStrusture1() : MyStrusture({ 1, new unsigned char[3] { 1, 2, 3 }, 3 }) {}
};
But this creates all kinds of problems, for example who is supposed to delete data
and when. My guess is that you don't want dynamic allocation at all, and the pointer in your base structure should actually be an array:
struct MyStrusture{
unsigned char code;
unsigned char data[3];
int size;
};
struct MyStrusture1 : MyStrusture
{
MyStrusture1() : MyStrusture({ 1, { 1, 2, 3 }, 3 }) {}
};
If the size should be variable, std::vector
can be used:
#include <vector>
struct MyStrusture{
unsigned char code;
std::vector<unsigned char> data;
int size;
};
struct MyStrusture1 : MyStrusture
{
MyStrusture1() : MyStrusture({ 1, { 1, 2, 3 }, 3 }) {}
};
Upvotes: 6
Reputation: 53016
In c++ you can just do it this way
class MyStruct
{
public:
MyStruct();
private:
unsigned char code;
unsigned char *data;
int size;
};
MyStruct::MyStruct() :
code(1)
, data(new unsigned char[3])
, size(3)
{
data[0] = 1;
data[1] = 2;
data[2] = 3;
}
Upvotes: 1