Surbhi Jain
Surbhi Jain

Reputation: 13

Why is the sizeof() output over the std::vector is different than the sizeof() of std::vector if vector is inside the class?

class c1 {
public:
std::vector<int> vc;
};

int main(int argc, char** argv) {

std::vector<int> v2;
std::cout << "Size 1" << sizeof (v2) << '\n';

v2.push_back(23);
std::cout << "Size 2" << sizeof (v2) << '\n';

c1 obj;
std::cout<<"\n Size of class is :"<<sizeof(obj);
std::cout<<"\n Size of class vector is :"<<sizeof(obj.vc);

obj.vc.push_back(25);
obj.vc.push_back(25);
obj.vc.push_back(25);
obj.vc.push_back(25);
obj.vc.push_back(25);
obj.vc.push_back(25);
obj.vc.push_back(25);
obj.vc.push_back(25);
std::cout<<"\n Size of class is :"<<sizeof(obj);
std::cout<<"\n Size of class vector is :"<<sizeof(obj.vc);

return 0;
}

Code Output :

Size 124
Size 224

 Size of class is :24
 Size of class vector is :24
 Size of class is :24
 Size of class vector is :24

In the above code, why the output of sizeof() on a vector and the output of sizeof() on the vector when the vector is inside the class are different. Please explain the output of this code.

Upvotes: 1

Views: 79

Answers (2)

tmlen
tmlen

Reputation: 9100

The size is 24 in both cases. In the output there is just the "1" of "Size 1" prepended, without space.

Adding elements into the std::vector does not change the size of the object: The actual elements are put into dynamically allocated memory managed by the std::vector. The std::vector itself contains only pointers etc. to its memory. A C++ object can never change size after it has been created.

To get the number of elements in the vector, use obj.vc.size().

Upvotes: 1

Nikita Smirnov
Nikita Smirnov

Reputation: 872

Because of typo, try this:

std::vector<int> v2;
std::cout << "Size 1 =" << sizeof (v2) << '\n';

v2.push_back(23);
std::cout << "Size 2 =" << sizeof (v2) << '\n';

Upvotes: 2

Related Questions