1

I am using pimpl idiom in my program and I am stuck in one place. My code is

Class*
Class::GetP()
{
return ClassImpl->GetP();
}

In my ClassImpl->GetP() I have

ClassImpl*
ClassImpl::GetP()
{
return pClassImpl;
}

As you can see I need to convert my pImpl bact to my caller type. What is the way?

I dont want to use any casting
Please advice

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
Yogi
  • 1,035
  • 2
  • 13
  • 39
  • What is the reason of not wanting to use any casting? – Alok Save Feb 16 '12 at 05:56
  • What is `GetP` supposed to be doing? Why do you need it? – tzaman Feb 16 '12 at 05:59
  • GetP actually returns a new instancde of some type which is made based on a parameter passed to getP, also i can use reintepret cast but it has some overheads. I think solution is simple and I am missing something – Yogi Feb 16 '12 at 06:03

1 Answers1

0

Wouldn't you simply do

Class *
Class::GetP()
{
    return this;
}

since callers of Class::GetP() shouldn't have a pointer to the internals anyway? (But then, what is that method for? It doesn't give the caller anything that they don't already have.)

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • actually its more like GetP(some param) it returns a new instance which is constructed in impl class using this parameter – Yogi Feb 16 '12 at 06:00
  • If it's returning a new instance, you should be creating a `new Class` somehow and returning that. So your implementation function would be `Class *ClassImpl::GetP(...) { ... }` (note the return type changed from `ClassImpl *` to `Class *`). – Greg Hewgill Feb 16 '12 at 06:19
  • so it it ok to create the instance of my caller in my pImpl class? – Yogi Feb 16 '12 at 06:30
  • The problem is the `GetP` function will have a lot of `ClassImpl->mem1`, `ClassImpl->mem2`, `ClassImpl->mem3`, which is quite messy hence the motivation to create a `GetP` in `ClassImpl`, but then we run into the problem of "convert pimpl back caller type". Is there a way to make it work by using OP's approach? – user3667089 Feb 01 '19 at 23:50