C++

How do you allocate memory for an object in C++2 min read

Class is not allocated any memory. This is partially true. The functions in a class are allocated memory which are shared by all the objects of a class. Only the data in a class is allocated memory when an object is created. Every object has its own memory for data (variables). For example consider the following Student class and its functions:

Now let’s create two objects for the above Student class as follows:




Student std1, std2;

C++ allows us to declare variables or functions as static members by using the keyword static.

Static Data

Syntax for declaring a static variable is as follows:

static data-type variable-name;

Static data members will have the following properties:

  • Only one copy of static data element will be created irrespective of the no. of objects created.
  • All objects share the same copy of the static data element.
  • All static data members are initialized to 0 when the first object for a class is created.
  • Static data members are only visible within the class. But their lifetime is throughout the program.

Take your time to comment on this article.

Leave a Comment