All the music pieces and songs are written on some scale, say if we consider D major scale the Cs and Fs must be sharp and others natural. But the Cs and Fs in that piece might be flat or natural at some points as well, or some other natural notes may be sharp at some point. So if we don't write the piece using only D major scale notes, what does it mean for the piece to be in D major? we could even change the signs without changing the melody and hence change the scale as if it does not really matter what scale we consider for the piece, am I right?
Also, when some music is on a pentatonic scale, is it the same? can we use other notes than the ones in the pentatonic scale, or should we just use those five notes?