-4
class player{
   public:
      int a;
}
int main(){
   player p1;
   p1.a=10;
}

I created a reference variable p1 of player but not the actual object on heap since I haven't used the new keyword on p1. But, c++ compiler allows me to assign value 10 to data member 'a' of p1. How is this possible without having an object on heap?

Deva Sedhu
  • 13
  • 2
  • 2
    Because it is on the stack aka local to the scope – Ed Heal Dec 09 '17 at 09:19
  • 1
    I c++ you can create things on heap with `new` or create them on stack. That's what you are doing here. This is not java. Read more about it. – Syntac Dec 09 '17 at 09:20
  • There are plenty of related question in the "Related" section, have a look. – Syntac Dec 09 '17 at 09:21
  • If you really just want a pointer (and btw. 'Reference' is something different than 'Pointer' in C++), then you need to declare `p1` with `player* p1`. – Syntac Dec 09 '17 at 09:22
  • 3
    `p1` is not a reference varaible. This is C++, not Java. They work differently. – Peter Dec 09 '17 at 09:29
  • I'm voting to close this question as off-topic because it is a question based on a false premise (that C++ and Java work in the same way, with a case where they explicitly differ). – Peter Dec 09 '17 at 09:31
  • 1
    How to use a variable is example 2 in my C++ book, right after the "Hello World!" example. Please read another page in *your* book. – Bo Persson Dec 09 '17 at 10:06
  • 1
    I'm voting to close this question as off-topic because it is a question based on a false premise (that C++ and Java work in the same way, with a case where they explicitly differ). – Jesper Juhl Dec 09 '17 at 10:12

1 Answers1

4

You are confusing C++ with Java. p1 is not a reference, it's just an object with automatic storage duration. It's created when the variable's scope begins, and it's destroyed when the variable's scope ends.

In C++, you normally only use the "heap" (the correct word would be: the free store) if you need more complex control over an object's lifetime.

If you don't need this special control, then an object in C++ works just like, say, an int or a double. You wouldn't feel it's necessary to write new int or new double, would you? Well, in C++, your player acts like an int or a double in this regard. It's a major difference to almost all other popular programming languages.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
  • thanks mate, you got me, I was confused between c++ and java. And I did a lot of research before asking the ques, so pls dont downvote it :( – Deva Sedhu Dec 09 '17 at 12:43