Reputation: 51
I apologize if this question has already been asked, but I could not find the same question. Please redirect me to the relevant question.
#include<iostream>
using namespace std;
class ABC
{
int a;
int &ref;
public:
ABC(int arg = 0):a(arg), ref(a){}
void mutate_func(int arg) const {
ref = arg;
}
void print_val() {
cout << endl << &a << "\t" << &ref;
cout << endl << a << "\t" << ref;
}
};
int main()
{
ABC abc_obj(5);
cout << sizeof(abc_obj);
abc_obj.print_val();
abc_obj.mutate_func(10);
abc_obj.print_val();
return 0;
}
I am trying to modify a data-member of a class inside a const member function through a reference variable which is part of the same class only.
I have two questions -
Why it is not throwing compilation error.
I am printing address of both variables and as expected both are showing same address, but still sizeof() for the instance is showing size as 8 bytes.
Upvotes: 2
Views: 160
Reputation: 264
I can answer the sizeof and address part.
A reference can be seen like a pointer with a lighter syntax so it needs storage space equivalent to a pointer (4 bytes here).
A reference is modified only during its initialization ref(a)
. After its initialization, any operation on the reference is performed on the referenced value, so &ref
gives the address of the referenced value and not the reference itself. So &a == &ref
makes perfect sense.
Upvotes: 1
Reputation: 506897
This is a class making it very easy to trigger undefined behavior. Just create a const object of it and call the const member function.
C++ supports the mutable
keyword for a supported mechanism of changing the bits of an object in a const member function.
Upvotes: 2