5

I know Class *cls is a pointer, and Class &cls takes the address, but what is

void fucction1( Class *&cls)

If I have Class c, what should I pass to function1()?

Thanks!

Wei Shi
  • 4,945
  • 8
  • 49
  • 73

4 Answers4

8

For a type T, T* is a pointer to an object of type T, so Class* is a pointer to a Class object.

For a type T, T& is a reference to an object of type T, so putting them together, Class*& is a reference to a pointer to a Class object.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
8

Besides, what James explained in his response, let me add one more important point to it.

While you can write Class* & (reference to pointer) which is perfectly valid in C++ only, you cannot write Class& * (pointer to reference), as you cannot have a pointer to a reference to any type. In C++, pointer to reference is illegal.

ยง8.3.2/4 from the language specification reads,

There shall be no references to references, no arrays of references, and no pointers to references.


If I have Class c, what should I pass to function1()?

You can write your calling code like this:

Class *ptrClass;

//your code; may be you want to initialize ptrClass;

function1(ptrClass);

//if you change the value of the pointer (i.e ptrClass) in function1(),
//that value will be reflected here!
//your code
Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0
Class c;
Class* c_ptr = &c;
function1(c_ptr);

Would work. But note that rvalue-references is only possible with C++0x which most compilers haven't fully implemented them. Thus the following wouldn't work:

Class c;
function1(&c);
langerra.com
  • 779
  • 3
  • 8
0

As said, a reference to a pointer to Class.

  • you pass a Class * to the function
  • the function may change the pointer to a different one

This is a rather uncommon interface, you need more details to know what pointers are expected, and what you have to do with them.

Two examples:

Iteration

bool GetNext(Classs *& class)
{
   if (class == 0)  
   {
     class = someList.GetFirstObject();
     return true;
   }

   class = somePool.GetObjectAbove(class); // get next
   return class != 0;       
}

// Use for oterating through items:
Class * value = 0;
while (GetNext(value))
   Handle(value);

Something completely different

void function (Class *& obj)
{
    if (IsFullMoon())
    {
      delete obj;
      obj = new Class(GetMoonPos());
    }
}

In that case, the pointer you pass must be new-allocated, and the pointer you receive you need to pass either to function again, or be delete'd by you.

peterchen
  • 40,917
  • 20
  • 104
  • 186