This is a question for curiosity, which I have not found the good answer yet. Suppose in "main.cc" I have the following code
namespace {
class MyClass {
public:
int GetNumber() const {return number_;}
MyClass(const int number) :
number_(number) {
}
private:
const int number_;
};
const MyClass* GetPointerToClass(const MyClass &c) {
return (&c);
}
} // namespace
int main(int argc, char* argv[]) {
const MyClass my_constant_class(5);
const MyClass* const pointer1_to_constant_class = GetPointerToClass(
my_constant_class);
printf("%d\n", pointer1_to_constant_class->GetNumber());
const MyClass* const pointer2_to_constant_class = &my_constant_class;
printf("%d\n", pointer2_to_constant_class->GetNumber());
const MyClass& reference_to_constant_class = my_constant_class;
printf("%d\n", reference_to_constant_class.GetNumber());
const MyClass copy_of_my_class = my_constant_class;
printf("%d\n", copy_of_my_class.GetNumber());
return 0;
}
Now when I run the program, it prints: 5 5 5 5
The thing I'm curious about is why the program compiles and runs successfully?
In particular (according to my understanding, correct if I am wrong):
value of pointer1_to_constant_class is assigned to a reference of a const reference.
value of pointer2_to_constant_class is assigned to a reference of an object.
(so although both pointers are of the same type, they are assigned to different types)
value of reference_to_constant_class is assigned to an object.
value of copy_to_my_class is assigned to an object.
(so reference and object are assigned to the same type)
So why we have to call pointer2_to_constant_class->GetNumber, if it is assigned to a reference of an object.
Also, why there is no difference in calling reference_to_constant_class.GetNumber(), versus copy_of_my_class.GetNumber(),
if one is an object, another just a reference?