c++ - Why class instance as pointer uses heap and not stack? -


i read in c++ book can have kinds of class instances in c++.

  1. normal class instances
  2. class instances pointer

for example :

class person { public:     person();     person(std::string name, int age){      } };      //this created in stack     :  person john("john",68);     //this created in heap     b :  person *marcel("marcel",31); 

so, why when creating object using pointer (a) uses heap , why in b, uses stack?

first, let's correct syntax:

int main() { person john("john",68);  //statement 1 person *marcel = new person("marcel",31); //statement 2 .... } 
  • the first statement, indeed, creates instance of class person, on stack.
  • the second statement declares pointer of type person on stack, , assigns instance of class person on heap, because dynamically allocated. so, pointer (i.e. variable holds address of class instance) resides on stack, actual instance allocated on heap.

i hope clears things up, if not, recommend going basics , looking pointers.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -