Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are truly doing C++, there is no practical difference between a class and a struct except the default member visibility - classes have private visibility by default while structs have public visibility by default. The following are equivalent:</p> <pre><code>struct PacketStruct { unsigned int bitlength; unsigned int data[]; }; class PacketClass { public: unsigned int bitlength; unsigned int data[]; }; </code></pre> <p>The point is, you don't need the CreatePacket(). You can simply initialize the struct object with a constructor.</p> <pre><code>struct Packet { unsigned long bytelength; unsigned char data[]; Packet(unsigned long length = 256) // default constructor replaces CreatePacket() : bytelength(length), data(new unsigned char[length]) { } ~Packet() // destructor to avoid memory leak { delete [] data; } }; </code></pre> <p>A few things to note. In C++, use new instead of malloc. I've taken some liberty and changed bitlength to bytelength. If this class represents a network packet, you'll be much better off dealing with bytes instead of bits (in my opinion). The data array is an array of unsigned char, not unsigned int. Again, this is based on my assumption that this class represents a network packet. The constructor allows you to create a Packet like this:</p> <pre><code>Packet p; // default packet with 256-byte data array Packet p(1024); // packet with 1024-byte data array </code></pre> <p>The destructor is called automatically when the Packet instance goes out of scope and prevents a memory leak.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload