1
#include<iostream>
using namespace std;

class Prac{
       string ch;
       public:
    void getstring(string g)
           {
            ch=g;
            return;
           }
         };
int main()
{
    Prac obj1;   
    Prac obj2;
    string str1;
    cout<<"Enter string for object 1"<<endl;
    getline(cin,str1);
    obj.getstring(str1);
    cout<<sizeof(obj1)<<endl;
    cout<<sizeof(obj2)<<endl;
    return 0;
}  

We know that the size of the object is the total size of the data members present in it. Here for the obj1 we are inserting some value for the string variable and for obj2 we are leaving it blank. Why won't there be any difference in the output(size of the objects)?

  • 2
    "We know that the size of the object is the total size of the data members present in it." - no, that is not true. "Why won't there be any difference in the output" - because size of the object does not depend on the data stored in in it. – AnT stands with Russia Aug 26 '17 at 15:11
  • 1
    `std::string` contains dynamically allocated memory that's not counted by `sizeof` – SurvivalMachine Aug 26 '17 at 15:12

2 Answers2

0

Well, as you said, the size of an object is (roughly) the size of all it's members combined.

But, you cannot add new members at runtime can you?

No. The size of an object is a compile time property of a type. If the size of your object is 24, it will never change, no matter what value you put in it!

It's like expecting the size of an int to be bigger if you assign a large value to it. No, the size is the same, but the value is different.

This is roughly the same thing happening here. You have a class that hold a std::string. A string holds a capacity, a size and a pointer to the string data. Assigning any value to those won't change the size of your struct.

The thing changed in size is the size of the allocated buffer your string is pointing to. But this doesn't change the size of the std::string class.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
0

First of all in C++ object sizes are determined at compile time. So size cannot change at runtime. Sizeof() actually returns size of the type. All objects of same type have the same size, by language design.

Then, there may be padding, unused bytes between members, so size of a type may actually be a bit larger than just size of all members.

But to answer your actual question: variable length data is not stored in the object itself. Memory for it is allocated separately, and object just stores a pointer to allocated data.

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176