Hello Guys,
We already learnt how to create a single object in this post. Now, let's try to create two objects with the same program.
For each object, memory space will be created freshly. Variables' memory space will be separate but not the functions' space. All object's variables will share the single member function.
#include <iostream> class Army // Class declaration { public: int number_suffix; // Member Variable string key; void enrollment(string name, int age) {key = name; number_suffix = age;} void retirement() // Member Functions {cout << key << " is retiring" << endl;} }; int main() { Army a1, a2; // Object creation and Memory allocation a1.enrollment("Shirley", 31); a1.retirement(); a2.enrollment("Vicky", 32); a2.retirement(); return 0; }
Generally, the class definition is in .h file. But the member function definition can be in .cpp file and all member function must qualify the class name ( Eg: Army::retirement() ) to avoid a free standing functions.
The takeaway is when the new object is created each time, fresh memory space is allocated. In case of member functions, they will be shared by all objects whereas member variables will be created separately.
References : Vedinesh Academy
Comments
Post a Comment