memory of a reference variable in c++?

Viewed 222

I've just started to learn Cpp from the basics and am confused when I came across reference variables.

From what I have learn't reference variables are just like an alias (another name to the same memory), so in this case it need need any memory.

When I ran the below code:

class sample_class
{
    public:
        int num; //line1
        int& refnum = num; //line2
}

int main()
{
    sample_class sample_object;
    cout<< "sample_class object size : " << sizeof(sample_object) <<endl;
    return 0;
}

I got the output as:

sample_class object size : 8

==>Here, the size for num is 4 bytes (32-bit compiler) and refnum since a reference is simply an alias to num. Then, why in this case, the size of object is 8?

==>Also, if really an refnum is like an alias then when does this information (info that refnum also holds/alias to the same memory address of num) gets stored?

Edited :

And consider this case (changine the definition of sample_class):

class sample_class
{
    public:
        char letter; //line3
        char& refletter = letter; //line4
        char letter_two; //line5
}

Here, If I print the object size of sample_class object, I get it as 12 (though the size of letter,refletter and letter_two are each equal to 1). But if I comment line 4, the object size is just 2. How is this happening???

I'm interested to learn from the basics, so if I'm wrong anywhere please correct me

3 Answers
Related