Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: struct and new keyword

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

like image 984
Dan Avatar asked Mar 05 '12 15:03

Dan


People also ask

Can we use new keyword with structure?

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.

Can you use new with a struct?

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.

Does new keyword work in C?

No, new and delete are not supported in C.

Is struct a keyword in C?

'struct' keyword is used to create a structure.


1 Answers

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.

like image 116
Fred Foo Avatar answered Sep 17 '22 01:09

Fred Foo