1

I have come across a program in which there is a class with name "A".

There is the following syntax in the declaration of a variable that I am not able to understand.

A& obj;

what does this mean and in what cases this is used.

user1198065
  • 210
  • 3
  • 10
  • Do you have a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) on hand? Such a book will cover this type of variable declaration and much, much more. – In silico Sep 27 '12 at 05:36
  • My comment had a link in it: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list Take a look at the "Beginner - Introductory" section. – In silico Sep 27 '12 at 05:41

1 Answers1

4

obj is a reference to an A object. Presumably this is a class data member, since references cannot be default initialized (they have to refer to something from the outset).

struct Foo
{
  int& a;
  Foo(int n) : a(n) {} // must be initialized in constructor initialization list.
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 2
    @user1198065 in situations when a "null" or "default" value makes no sense, a reference might be a better choice. You know it has to refer to something in a well formed program. – juanchopanza Sep 27 '12 at 05:37
  • 2
    @user1198065: A pointer can in fact be used in this situation, but references are preferred since they are generally safer to use than pointers. A reference can't be set to null in well-formed programs, as juanchopanza has mentioned. – In silico Sep 27 '12 at 05:39