How does sizeof work in C++?

Shervan360 1,681 Reputation points
2022-04-30T23:06:36.457+00:00

Hello,

I read:

The memory space is allocated to the data members of a class only when an object of the class is declared, and not when the data members are declared inside the class.

>

Why does sizeof(Base) 44?

I didn't create an instance of the Base class and expected the compiler doesn't allocate memory for Base.

Please see the following code:

#include <iostream>
using namespace std;

class Base
{
public:
    void Print() {
        cout << "In Base..";
    }
    int a;
    int arr[10];
};


int main() {

    cout << sizeof(Base) << endl; // 44


    return 0;
}
Developer technologies | C++
{count} votes

Accepted answer
  1. RLWA32 49,901 Reputation points
    2022-04-30T23:19:53.683+00:00

    The compiler did not allocate any memory for your class. What it did do is determine how many bytes of storage it would take if such a class was created. I suggest you read sizeof-operator

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.