# pointer to object

.

---

## 🧠 What is a Pointer to an Object?

In C++, a **pointer to an object** is just like a pointer to any other data type —  
it stores the **address** of an object rather than the object itself.

👉 Instead of directly working with the object, you work through its **memory address**.

---

### 🧩 Example 1 — Basic Idea

```plaintext
#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Student s1;             // Normal object
    s1.name = "Amit";
    s1.age = 21;

    Student *ptr = &s1;     // Pointer to object

    // Access members using ->
    ptr->display();         // same as s1.display()

    return 0;
}
```

---

### 🧱 Explanation

| Concept | Meaning |
| --- | --- |
| `Student s1;` | Creates an object `s1` |
| `Student *ptr = &s1;` | Pointer `ptr` stores the **address** of `s1` |
| `ptr->display();` | `->` operator is used to access members **through pointer** |
| `.` vs `->` | `.` is used with normal objects, `->` is used with pointers |

---

### 💡 You can also use `(*ptr).member`

This means the same as `ptr->member` but is less clean:

```plaintext
(*ptr).display();  // same as ptr->display()
```

---

### 🧩 Example 2 — Pointer to Dynamically Allocated Object

```plaintext
#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int price;

    void show() {
        cout << "Brand: " << brand << ", Price: " << price << endl;
    }
};

int main() {
    Car *c = new Car;   // dynamically create an object on heap

    c->brand = "Tesla";
    c->price = 80000;

    c->show();

    delete c;           // free memory
    return 0;
}
```

🧠 Here:

* `new Car` → allocates object in heap memory
    
* `Car *c` → stores address of that object
    
* Use `->` to access members
