Reputation:
Here, Student_info is a class. I am trying to initialize it with strings of different length but it always give the same size of object, when it is supposed to be dependent on the input string length. Any suggestions? (Name and Company are defined as string variable, not as char arrays)
Structure of class Student_info
{ string name, company;
int yr, age;
}
Student_info *s[5];
s[0]= new Student_info("Aakash Goyal","form MNNIT Allahabad",2,57);
cout<<endl<<s[0]->getCompany()<<" is the company"<<endl;
cout<<endl<<s[0]->getName()<<" is the name and the size is: "<<sizeof(*s[0]);
s[1]= new Student_info("Hare Krishna","Hare Krsna Hare Rama",1,34);
cout<<endl<<s[1]->getCompany()<<" is the company"<<endl;
cout<<endl<<s[1]->getName()<<" is the name and the size is: "<<sizeof(*s[1]);
Upvotes: 0
Views: 124
Reputation: 36630
sizeof()
is a compile time operator. At runtime, it will always return the same constant value for a given object.
Even if you include a std::string
in your object, and assign different values to it, the size of the enclosing object as calculated by sizeof()
will remain the same since the data buffer which holds the string is handled internally by std::string
(essentially through a pointer, which again has a constant size independent of the data it points to).
If you want to get the runtime length of a string, use its length()
method.
Upvotes: 2
Reputation: 437386
The result of sizeof
is always constant for a given type, including std::string
and your own type Student_info
that aggregates strings. This is easy to see by induction: since every type is built by aggregating primitives (numeric types, pointers, etc) and all primitives have a fixed size, then any type you can make from them will also have a fixed size.
Types that store a variable amount of data such as std::string
, std::vector
and others do this by aggregating a pointer to a memory region where their data is stored. The size of that region is not constant, but the size of the pointer (and therefore the containing class) is.
Upvotes: 3