why this compile ?

why does this code compile ?
I thought you need to initialize reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class lol
{
private :
    int& wat;
public :
    lol(int& haha) :
        wat(haha)
    {}
    int& access()
    {
        return wat;
    }
};

int main()
{
    int haha = 90;
    lol a{haha};
    std::cout << a.access();
}
Last edited on
It's initialized in the constructor on line 9.
I see...thank you my friend
but I thought it have to be initialized at the line it is declared ?
Because it is a member, you can safely initialize it in the initializer list.
ah I see....thank you
so is it good to use it or should I use smart pointers
Last edited on
Because it is a member, you can safely initialize it in the initializer list.

I believe you actually must initialize it in the initializer list.
so is it good to use it or should I use smart pointers

It depends. You certainly can't use smart pointers with the code you've written. If you did then you'd end up trying to delete the local variable haha, causing undefined behavior in your program.

Should your class own the item that gets passed in? Use a unique_ptr. Should it share ownership? Use a shared_ptr. Does it need to worry about whether the value passed in goes out of scope before the class does? Probably.

My point is that you should figure out what behavior you require first, then decide how to make your code model the behavior, rather than picking a code model and hoping for the best.
I see...thank you my friend
but I thought it have to be initialized at the line it is declared ?

To be more specific, you have to bind a reference when it is created; in other words, at initialisation-time. You cannot bind it after creation by assigning anything to it.

However, at line 6, you are not creating the reference. You are simply defining your lol class, and declaring that it contains a data member that is a reference.

A data member gets created when the object it's part of gets created. So, in this case, it gets created when a lol object gets created. This is why we bind the reference in the initialisation list in the constructor, because the constructor is invoked at the point where the object is created.

Does that make sense now?
Last edited on
after more than a week and 2 days of cplusplus broken
I will proudly answer yes
Topic archived. No new replies allowed.