0

I want to pass a pointer of pointer of object to a function but get the error

invalid conversion from 'CustomInterface**' to LocalLogger**'

I try something like this:

class LocalLogger
{}
class CustomInterface: public LocalLogger
{}

foo(LocalLogger** const obj)
{
    // do something
}

bar()
{
    CustomInterface** p_p_obj;
    CustomInterface* p_obj = new CustomInterface();
    p_p_obj = &p_obj;
    foo(p_p_obj);                      // <-- here is the error
}

This is very simplified but I need the pointer to pointer.

Psy-Kai
  • 187
  • 3
  • 13
  • 4
    Why do you need to pass a pointer to pointer? Sounds unlikely. `LocalLogger**` says that you want a pointer to a `LocalLogger*`, but you are giving a pointer to a `CustomInterface*`. These are not compatible. Just because `CustomInterface` derives from `LocalLogger`, doesn't mean `CustomInterface*` derives from `LocalLogger*` (only class types can be derived). – Joseph Mansfield Jul 10 '14 at 09:55
  • I have multiple CustomInterface-instances (stored in a hash). LocalLogger and some other classes hava to point to one CustomInterface-instance. I set *p_p_obj to one CustomInterface-instance and LocalLogger and the other classes can work directly with this instance. So when I switch to an other CustomInterface-instance I don't need to pass this instance everytime to every class, which need it. – Psy-Kai Jul 10 '14 at 10:15
  • @Psy-Kai If that is indeed what you're trying to accomplish then I'm dropping my answer and volleying al support into Joseph's corner on this one. The fundamental premise is flawed in your approach. You should be passing a `LocalLogger**`exclusively, not a pointer to pointer-to-type derived from said-same. – WhozCraig Jul 10 '14 at 10:20
  • It's still not clear why you need a pointer to pointer. Why can't you just deal with single pointers? – Joseph Mansfield Jul 10 '14 at 10:20
  • @JosephMansfield He's potentially swapping out the dynamic object the p2p holds with one of a different type (it may be `SomeClass*` going in, but he wants `SomeOtherClass*` coming out). Neither a ref2p nor a p2p will solve this unless they are actual `LocalLogger` I both get what the OP is trying and firmly agree with you (odd as that sounds). – WhozCraig Jul 10 '14 at 10:24
  • would it be a better method, to create a struct which only holds a pointer and then pass/store a reference to the struct? – Psy-Kai Jul 10 '14 at 12:05

1 Answers1

6

The compiler won't allow you to do this, for good reason. Consider:

class A { };
class B : public A { };
class C : public A { };

void make_an_A(A** out) { *out = new B(); }

C* pC;
make_an_A(&pC); // Doesn't compile.

If it allowed a C** to convert to A**, you would have been able to store a pointer to B in a pointer to C without using a cast, which is very bad.

T.C.
  • 133,968
  • 17
  • 288
  • 421