example3_heap_allocation_for_objects.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>

class Person {
public:
    Person(const std::string& name, int age) : name_(name), age_(age) {
        std::cout << "Person created: " << name_ << std::endl;
    }
    ~Person() {
        std::cout << "Person destroyed: " << name_ << std::endl;
    }
    void introduce() const {
        std::cout << "I'm " << name_ << ", " << age_ << " years old." << std::endl;
    }

private:
    std::string name_;
    int age_;
};

int main() {
    // Create an object on the heap
    Person* person = new Person("Alice", 30);

    person->introduce();

    // Deallocate the object
    delete person;

    return 0;
}
Back to heap