I was surprised by subobject references

Just thought this was interesting. I had a typo where I put "const Blah" instead of "const Blah&", and I thought that would make it copy the object's contents by value, but the const reference within the object being copied by value remained as a proper reference.

That is, even though (&fooBar != &foo.fooBar), (&fooBar.bruh == &foo.fooBar.bruh).

I guess I get why it happens; it's sort of like having a pointer in a subobject (and also otherwise what would happen if FooBar::bruh wasn't const), but I was a bit surprised.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

struct FooBar {
    FooBar( const bool& bruh )
      : bruh( bruh )
    { }

    int dummy = 42; // to prevent addresses being same as object
    const bool& bruh;
};

class Foo {
public:
    Foo(const FooBar& fooBar)
     : fooBar(fooBar)
    { }
	
    int dummy = 42;
    const FooBar fooBar;
};


void print(bool& bruh, FooBar& fooBar, Foo& foo)
{
	const char* spacing = "        ";
	cout << "bruh   [" << spacing << "][" << spacing     << "][" << &bruh            << "]: " << bruh << '\n';
	cout << "FooBar [" << spacing << "][" << &fooBar     << "][" << &fooBar.bruh     << "]: " << fooBar.bruh << '\n';
	cout << "Foo    [" << &foo    << "][" << &foo.fooBar << "][" << &foo.fooBar.bruh << "]: " << foo.fooBar.bruh << "\n\n";
}

int main()
{
	bool bruh = true;
	FooBar fooBar(bruh);
	Foo foo(fooBar);

	print(bruh, fooBar, foo);

	bruh = false;
	print(bruh, fooBar, foo);
}

bruh   [        ][        ][0x61fe1f]: 1
FooBar [        ][0x61fe00][0x61fe1f]: 1
Foo    [0x61fde0][0x61fde8][0x61fe1f]: 1

bruh   [        ][        ][0x61fe1f]: 0
FooBar [        ][0x61fe00][0x61fe1f]: 0
Foo    [0x61fde0][0x61fde8][0x61fe1f]: 0
Last edited on
I had a typo where I put "const Blah" instead of "const Blah&"
Where did you do this?

but the const reference within the object being copied by value remained as a proper reference
Yes, a reference can be initialized (by constructor) but not copied later.
I find it helpful to think of a reference as a synonym for another variable. Thought of this way, it makes sense that copying the synonym means that the copy refers to the same variable.
Topic archived. No new replies allowed.