Reputation: 6464
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
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
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
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
Reputation: 67175
Just get the address of the object.
some1 *p = &obj;
Or in your case:
func2(&obj, &obj2);
Upvotes: 17