I'm a beginner to C++, I've got the following piece of code:
struct Airline {
string Name;
int diameter;
int weight;
};
Airline* myPlane = new Airline;
my question is when I call the method new
it allocates memory, if I recall correctly. How does the PC know how much memory to allocate,especially given that there is a string type in there?
Thanks
We can instantiate Struct using the new keyword as well as using Pointer Address Operator in Golang as shown in the below example: Example: Here, you can see we are instantiating a Struct using new keyword.
Any struct or class can use either. new is a choice, and it means something. C# doesn't give you a choice. Classes are always in the heap, and structs are always on the stack.
No, new and delete are not supported in C.
'struct' keyword is used to create a structure.
An std::string
object is fixed-size; it contains a pointer to an actual buffer of characters along with its length. std::string
's definition looks something like
class string
{
char *buffer;
size_t nchars;
public:
// interface
};
It follows that your Airline
objects also have a fixed size.
Now, new
does not only allocate; it also initializes your object, including the std::string
, which means it probably sets the char
pointer to 0
because the string is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With