(I'd like to apologize for any false sense of authority that comes off through the formatting of my answer, but I thought the use of headings made it more readable.)
Using "sir" with strangers
I'm about to oversimplify, but as a rule of thumb you can consider it a neutral way to address anyone whose name you don't know. In most interactions with strangers, no one will really care whether you use "sir" or don't, as long as you're courteous overall:
"Excuse me, do you know what time the train leaves?"
"Ten o'clock."
"Thank you."
But it might come in handy if it's the only way you can get their attention.
"Sir? Sir! You dropped your wallet."
Of course, you generally wouldn't use it with someone you actually consider inferior (a small child would be the main justified case of this, but some people are just rude). In cases where perceived social standing is actually in question, it may be a good way to show that you do respect the other person.
Using "sir" with respected individuals
When directed at someone whose name you do know, that, counterintuitively, is when it becomes a term of respect.
With someone you consider a peer, you'd usually use their name once you learn it. By continuing to use "sir", you show that you don't consider yourself worthy of speaking to them as an equal. This is almost always expected in a structured hierarchy like a workplace or military command, but it's also a common way to show genuine, voluntary deference to a respected individual. (If they insist you use their name, though, do it!)
A final note
Apply all the same guidelines to "ma'am"/"miss" when speaking to a female. The only hangup is whether to use "ma'am" or "miss" in a given case, but that's another issue entirely, one you're probably familiar with and can find plenty of resources dedicated to if you don't.
Hope this is helpful, any corrections are welcome.