Re: Inheritance question
On Oct 26, 4:36 pm, Andrea Crotti <andrea.crott...@gmail.com> wrote:
I'm doing a project which has to manipulate some network data.
They suggested me to use the classical big buffer with the many memcpy,
but since we're in C++ I don't see why not using classes instead of
structs.
So I thought something like
--8<---------------cut here---------------start------------->8---
Packet:
char type;
const char *buffer;
Beacon : Packet
int nr;
...
--8<---------------cut here---------------end--------------->8---
1. what does the "sizeof" return on a class exactly?
The number of bytes an object of the class type occupies in an
array.
And (can I/does it make sense to) overload it?
You can't overload it; allowing this would break some important
invariants in the language.
2. does it make sense to keep the pointer to the content in "Packet"?
Or would be better to create then another class
"PacketHeader" and then Packet is the sum of both
Not sure, but generally, I'd think I'd make Packet a base class,
with an std::vector<char> (or std::vector<unsigned char>) for
the buffer which contains the actual network data.
3. how would I pack the data?
By pack, I presume you mean marshall.
something like?
void Packet::pack(const char *buffer) {
memcpy($first_field, ...)
}
That doesn't work, except in a few very limited cases. You have
to actually marshal the data, depending on its defined format.
Then of course the sanity checks for the dimension must be done
outside this
4. about inheritance, if I have a constructor like
Packet(char type, ..)
then I can implement it for example with
Packet::Packet(char type) : type(type)
right?
Yes. But if you're using inheritance, you probably don't need
the type.
I'd probably go with some sort of Buffer class to manage the raw
memory, to handle reading and writing, and perhaps to marshall
the basic types, then a Packet base class, which "owns" the
Buffer, once it has been created, and a derived class for each
type of packet. (To do this efficiently, you'll probably want
to dynamically allocate the buffer, and manage it using smart
pointers.)
But what should I then do then in Beacon?
Create one constructor with the same arguments seem to not work in
general...
You'll have to forward the arguments from the derived class
constructor. Normally, however, about the only argument I see
is the buffer.
--
James Kanze