123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- #include <iostream>
- // Cat class definition
- class Cat {
- public:
- static int HowManyCats; // Static data member to keep track of the number of Cat objects
- // Constructor that takes age as a parameter
- Cat(int age) : age(age) {
- ++HowManyCats;
- }
- // Destructor
- ~Cat() {
- std::cout << "destructing of the cat!" << std::endl;
- --HowManyCats;
- }
- // Static member function to get the number of Cat objects
- static int GetHowMany() {
- return HowManyCats;
- }
- private:
- int age; // Age of the cat
- };
- int Cat::HowManyCats = 0; // Initialize static data member
- // Function to create an array of 5 Cat objects with ages 1, 2, 3, 4, 5
- void creating() {
- std::cout << "before the Cat array is created, the number of the cat is:" << Cat::GetHowMany() << std::endl;
- Cat* cats[5]; // Array of pointers to Cat objects
- // Create 5 Cat objects with ages 1, 2, 3, 4, 5
- for (int i = 0; i < 5; ++i) {
- cats[i] = new Cat(i + 1);
- }
- std::cout << "after the Cat array is created, the number of the cat is:" << Cat::GetHowMany() << std::endl;
- // Delete the 5 Cat objects to free memory and reduce the count
- for (int i = 0; i < 5; ++i) {
- delete cats[i];
- }
- }
- int main() {
- std::cout << "before the function, the number of the cat is:" << Cat::GetHowMany() << std::endl;
- creating();
- std::cout << "after the function, the number of the cat is:" << Cat::GetHowMany() << std::endl;
- return 0;
- }
|