Reputation: 16928
As far as I know, References need to be declared and initialized at the same time.
I guess, its only use lies in passing arguments and in some cases Polymorphism.
Is it possible to keep a reference as a data member in a class?
If yes, when should we need that?
Please give me an example.
Upvotes: 2
Views: 625
Reputation: 14051
You would use a reference as a class member when it is an integral part of the class, without which the class cannot function, and you want to either share this part among several classes or use it polymorphically:
class Presenter
{
IView & view;
IModel & model;
Presenter(IView & view, IModel & model)
: view(view), model(model)
{
}
};
A reference member cannot be changed after construction, so using one makes a strong statement about how the class is meant to be used. Using regular or smart pointers offers more flexibility.
Upvotes: 5
Reputation: 14004
As don has pointed out a reference member can be used in much the same way as a pointer member. I think it is worth pointing out though that pointers can also be null and also be reseated so are much more useful in most respects.
additionally, in modern C++ you probably wouldn't use a pointer or reference member as you can use shared_ptr or unique_ptr to better encapsulate the lifetime of the members
Upvotes: 0
Reputation: 355079
You can have reference-type data members, but as a general rule you should not declare reference-type data members. A class with a reference-type data member is not assignable (because references are not assignable); this greatly restricts the use of the class.
It's almost always preferable to use pointer-type data members, since they effectively provide the same capabilities, with the same lifetime constraints, but without making the class not assignable.
Upvotes: 2