Search code examples
c++classobjectoopcomputer-science

No memory is allocated while creating the class, then where variables in the class saved?


In object oriented programming, there is concept of class and objects. We define a class and then create its instance (object). Consider the below C++ example:

class Car{
  public:
   string model;
   bool petrol;
   int wheels = 4;
}

int main(){
   Car A;
   cout << A.wheels;

   return 0;
}

Now I know no memory was allocated to the class Car until the object A was created. Now I am swamped in the confusion that if no memory was allocated to the Car, then at the time of creating object A, how object A will know that wheels is equal to 4 ? I mean it should be saved somewhere in the memory.

Please ignore mistakes as it is a question from beginner's side :)


Solution

  • There are 2 types of storage at work here.

    The information about Car is stored in memory. That is the code in its methods, its layout, including the literal value 4 which initializes wheels. This exists in the binary executable file, and exists in memory at all times your application is running.

    But when you say "no memory allocated.." you're thinking about memory of an instance of Car, where memory is allocated each time you create a new instance.