Re: basic question about references

From: Ben Cottrell (
Date: 01/09/05

Date: Sun, 09 Jan 2005 03:30:14 +0000

zapro wrote:
> Hello, I am learning C++ and having problems understanding references.
> Considering this piece of code:
> class NumSequence1 {
> protected:
> NumSequence1(std::vector<int> &re)
> : _relems(re) {}
> std::vector<int> &_relems;
> };
> class Fibonacci1 : public NumSequence1 {
> public:
> Fibonacci1()
> : NumSequence1(&_elems) {} // ERROR
> // ....
> protected:
> static std::vector<int> _elems;
> };
> this code doesn't compile and reports the errors:
> error: no matching function for call to
> `NumSequence1::NumSequence1(std::vector<int, std::allocator<int> >*)'
> error: candidates are: NumSequence1::NumSequence1(const NumSequence1&)
> error: NumSequence1::NumSequence1(std::vector<int, std::allocator<int> >&)
> If I remove the ``&'' from the Fibonacci1 constructor everything
> compiles, but I don't exactly understand why. My understanding is that
> since NumSequence1 accepts references, I would use the symbol & in the
> member initialization list ( NumSequence1(&_elems) ) in class
> Fibonacci1. Why don't I have to do that?

first of all remember that & is the 'Address Of' Operator.
   so, &_elems is 'Address of _elems' .. You would be passing the
address, rather than the object

The NumSequence1 constructor accepts objects of the type
std::vector<int> - it does not accept addresses.

Furthermore, by declaring NumSequence1(std::vector<int> &re) you have
specified that "re" is a Reference to an object, so "re" is not an
object itself.

you could think of a reference in this context like an alias or nickname
- You will be referring to an existing object somewhere else in the
program, but doing so under the name "re".

If, on the other hand, "re" was a pointer to a std::vector<int> instead
of a reference, then you would be correct in passing &_elems, since "re"
would be an object who's data type is 'address of std::vector<int>'.