Technical Interview

Tips, questions, answers and puzzles at
www.technical-interview.com

Wednesday, June 30, 2010

What are references in C++? Why do you need them when you have pointers?

What are references in C++? Why do you need them when you have pointers?

Answer:


A reference variable is actually just a pointer that reduces syntactical clumsiness related with pointers in C (reference variables are internally implemented as a pointer; it’s just that programmers can't use it the way they use pointers).

As a side note, a reference must refer to some object at all times, but a pointer can point to NULL. In this way, references can be more efficient when you know that you'll always have an object to point to, because you don't have to check against NULL:
void func(MyClass &obj)
{

obj.Foo();

}
Is better than:
void func(MyClass *obj)
{

if (obj) obj->Foo();

}

No comments:

Post a Comment