From 40, we can subtract the 12 that liked neither.
This gives us 28.
So, to find the ones that like both, add the 18 that like apple pie and the 15 that like chocolate cake and subtract 28 from this.
So 18 + 15 - 28 = 5 liked both.