c++ default constructor

I have a class like this example:

Class Customer
{
public:
string name;

}

it has a default constructor (that does nothing). when i create an object like this

newCustomer = new Customer;

what is the size of the name string? how does it allocate memory for this? i just need it to hold about 30 characters at the most and want to make sure it's not creating a huge memory space for it.
name is created by calling the default std::string constructor, making name an empty string.
does it keep creating new memory space each time i insert a letter into it or is it fixed?
closed account (zb0S216C)
bradleyy1012 wrote:
"what is the size of the name string?"

Implementation-defined. The implementation may implement "std::string" in anyway it wants, so long as it abides by the rules stated in the C++ standard. Use "sizeof()" to query the size of class, or piece of storage.

bradleyy1012 wrote:
"how does it allocate memory for this?"

The data members of "Customer::name" are pushed onto the program's stack. The memory allocated internally to "Customer::name" is allocated prior to "newCustomer"'s construction.

bradleyy1012 wrote:
"i just need it to hold about 30 characters at the most and want to make sure it's not creating a huge memory space for it."

http://www.cplusplus.com/reference/string/string/reserve/

bradleyy1012 wrote:
"does it keep creating new memory space each time i insert a letter into it or is it fixed?"

Only if it needs more memory.

Wazzak
Last edited on
The size of the data member name is equal to

sizeof( std::string ).

You can know how much memory this object occupies by executing the simple code

1
2
3
4
5
6
7
#include <iostream>
#include <string>

int main()
{
   std::cout << "sizeof( std::string ) = " << sizeof( std::string ) << std::endl;
}


Usually the memory for values entered in an object of type std::string is allocated dynamically and does not influence on the size of your class Customer.
Last edited on
Topic archived. No new replies allowed.