Mark
Mark

Reputation: 6464

convert reference to pointer representation in C++

Is there a way to "convert" a reference to pointer in c++? In example below, func2 has already defined prototype and I can't change it, but func is my API, and I'd like to either pass both parameters, or one (and second set to NULL) or neither (both set to NULL):

void func2(some1 *p1, some2 *p2);

func(some1& obj, some2& obj2)
{
   func2(..);
}

Upvotes: 46

Views: 80310

Answers (6)

Mehrdad Nazmdar
Mehrdad Nazmdar

Reputation: 192

Cast the function to a new function:

void func2(some1 *p1, some2 *p2);
//Just add the following line of code:
void (*func)(some1&,some2&) = (void(*)(some1&,some2&))&func2;

int main() 
{
    some1 obj();
    some2 obj2();
    func(obj,obj2);
}

Upvotes: 0

Jarod42
Jarod42

Reputation: 217065

In normal cases, you can simply use &:

void func(some1& obj, some2& obj2)
{
    func2(&obj, &obj2);
}

but operator& might be overloaded, so std::addressof (since C++11) should be used for those cases:

void func(some1& obj, some2& obj2)
{
    func2(std::addressof(obj), std::addressof(obj2));
}

Upvotes: 13

user2249683
user2249683

Reputation:

For a clean design put all in a class (or use namespaces)

class X {
   private:
   void func2(someA*, someB*);

   public:
   func(someA& a, someB& b) { func2(&a, &b); }
   func(someA& a) { func2(&a, 0); }
   func() { func2(0, 0); }
}

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67175

Just get the address of the object.

some1 *p = &obj;

Or in your case:

func2(&obj, &obj2);

Upvotes: 17

Umer Farooq
Umer Farooq

Reputation: 7486

 func2(&obj, &obj2);

is what you should use.

Upvotes: 5

Chen
Chen

Reputation: 1180

func2(&obj, &obj2);

Use reference parameters like normal variables.

Upvotes: 46

Related Questions