8

I'm using a library which has a draw function which takes a reference to a circle. I wish to call this function but I have a pointer to my circle object. Can I pass this pointed to object to the draw function? If not, why not?

Thanks,

Barry

Baz
  • 12,713
  • 38
  • 145
  • 268

4 Answers4

15

Yes you can.

You have this function

void DoSth(/*const*/Circle& c)
{
   ///
}

You have this pointer

/*const*/ Circle* p = /*...*/;

You call it like this

DoSth(*p);

I suggest that you should read a good C++ book. This is really fundamental stuff.

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
6

As long as pointer is not destroyed while the reference is still being used it is fine.

int *p = new int;
int &r = *p;
Tom Kerr
  • 10,444
  • 2
  • 30
  • 46
5

Yes you can, just dereference the pointer, example:

void functionToCall(Circle &circle);

//in your code:
Circle *circle = new Circle();
functionToCall(*circle);
Wodzu
  • 6,932
  • 10
  • 65
  • 105
bcsanches
  • 2,362
  • 21
  • 32
5

It would be easier if you'd supply some code of your problem. But basically it would work like this:

void func(Circle& circle) {
    // do something
}

...
Circle *pCircle = new Circle();
func(*pCircle);
Constantinius
  • 34,183
  • 8
  • 77
  • 85