SuperFamousGuy
SuperFamousGuy

Reputation: 1575

How do I pull a reference from a pointer?

Forgive me as my C++ is very rusty. But I am in a bind. I am trying to make a custom list that have methods to return the front most, and back most items.

ElementType& front() throw(string*)
{
   if (empty())
      throw new string("Empty Vector");
   else
      return(first)
}

My main problem is that I don't have the actual first item, I have a pointer to it and I have no idea how to go about taking a reference of what the pointer is pointing it, using only the pointer. I've tried things similar to:

ElementType& *first

or

&*first

but I can't get them to play nicely. Any advice would be greatly appreciated.

Upvotes: 1

Views: 225

Answers (4)

bmargulies
bmargulies

Reputation: 100196

int& intRefFunction() {
  static int intValue = 42;
  static int* intPointer = &intValue;
  return *intPointer;
}

Upvotes: 1

sashang
sashang

Reputation: 12254

ElementType& *first

Is not legal. You can't have a pointer to a reference.

Just derefence the pointer and you will have a reference to it.

Example, assuming first is a pointer:

ElementType& r(*first)
return r

Upvotes: 0

beldaz
beldaz

Reputation: 4491

ElementType& *first

Declares a variable first to be, I think, a pointer to a reference to an ElementType object. I'm not sure that is even valid C++.

&*first

If you return this, you are returning the address of the dereferenced object pointed to by pointer first, which I believe amounts to just returning first.

If first is a pointer to the first ElementType item, just return the dereferenced object as *first.

By the way, that's not the only thing that looks wrong with your code. I don't think throwing string pointers is good practice (throw an object derived from std::exception, such as std::out_of_range), nor is including the exception specification (it incurs unnecessary overhead). So you're probably after something more like this:

ElementType& front()
{
   if (empty()) {
      throw std::out_of_range("Empty Vector");
   }
   return *first;
}

Upvotes: 0

K-ballo
K-ballo

Reputation: 81409

If first is a pointer to your element, *first will give you a reference to it.

Upvotes: 4

Related Questions