Once a class is defined, it can be used to create variables of its type known as objects. The relation between an object and a class is the same as that of a variable and its data type.
The syntax for declaring an object is
class_name = object_list;
class_name = the name of the class
object_list = a comma-separated list of objects
To understand the concept of instantiation, consider this example.
Example : Declaring objects of a class
II body of the class
int main ()
book bookl, book2, book3; //objects of class book
In this example, three objects namely, book1, book2 and book3 of the class book have been created in main ().
Note that the syntax for the declaration of objects of a particular class is same as that for the declaration of variables of a built-in data type. To understand this concept, consider these statements.
int a,b,c; // declaration of variables
book bookl, book2, book3; // declaration of objects
Like structures, objects of a class can also be declared at the time of defining the class as shown here.
Hence, the objects of the class book can also be declared with the help of these statements.
// body of class
}bookl,book2,book3; // declaration of objects
Memory Allocation for Objects
Before using a member of a class, it is necessary to allocate the required memory space to
that member. The way the memory space for data members and member functions is allocated is different regardless of the fact that both data members and member functions belong to the same class.
The memory space is allocated to the data members of a class only when an object of the class is declared, and not when the data members are declared inside the class. Since a single data member can have different values for different objects at the same time, every object declared for the class has an individual copy of all the data members.
On the other hand, the memory space for the member functions is allocated only once when the class is defined. In other words, there is only a single copy of each member function, which is shared among all the objects. For instance, the three objects, namely, book1, book2 and book3 of the class book have individual copies of the data members title and price. However, there is only one copy of the member functions getdata () and putdata () that is shared by all the three objects