7

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
  • 11,687
  • 35
  • 137
  • 244

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
  • 125,569
  • 56
  • 315
  • 427
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,094
  • 2
  • 28
  • 44
5

Yes you can, just dereference the pointer, example:

void functionToCall(Circle &circle);

//in your code:
Circle *circle = new Circle();
functionToCall(*circle);
Wodzu
  • 6,793
  • 9
  • 60
  • 101
bcsanches
  • 2,273
  • 21
  • 30
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
  • 32,691
  • 7
  • 72
  • 83