2

Possible Duplicate:
Pointer vs. Reference

I am wondering if there any benefits in using references instead of pointers on some interface. Being more specific let's consider small example:

struct MyInterface {
   virtual ~MyInterface() {}
   virtual void f() = 0;
};

class MyClass : public MyInterface
{
   virtual void f()
   {
      std::cout << "F()" << std::endl;
   }
};


void myFunction(MyInterface& obj);

int main(int argc, char *argv[])
{
   MyInterface* pObj = new MyClass;

   myFunction(*pObj);

   delete pObj;

   getchar();
   return 0;
}

void myFunction(MyInterface& obj)
{
   obj.f();
}

In myFunction instance of MyClass can be passed as a pointer, what is written in many books. My question is what can be considered as a good practice (pointer or reference) and what is more efficient?

Sorry if this question somehow was asked previously.

Community
  • 1
  • 1
besworland
  • 747
  • 2
  • 7
  • 17

2 Answers2

3

Once a value is passed, passing a reference is, performance wise and semantics wise, the same as passing a pointer. In the example you wrote, you are passing a reference obtained from a pointer, so the limitations imposed by reference-input function are invalidated here. Indeed, if you wrote

MyInterface* pObj = 0;
myFunction(*pObj);

You would get a runtime error. But the error is because you are doing

myFunction( *0 );

i.e., because you are dereferencing a null pointer, not because you are passing the zero value. In fact,

myFunction( 0 );

will give you a compile-time exception (which is great).

2

It depends upon your need.

Use pointer:

  • If there's ever a chance that you could want to pass "no object"
  • If you want ability to point the passed pointer to different location
  • If you want to get address of pointer variable for some reason

else use reference. A reference is more like a alias to a variable than a pointer to it. This semantics opens some possible optimizations for the compiler and makes it efficient than pointer.

sahaj
  • 822
  • 5
  • 17