Skip to main content

Command Palette

Search for a command to run...

pointer to object

Published
2 min readView as Markdown

.


🧠 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

#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

ConceptMeaning
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:

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

🧩 Example 2 — Pointer to Dynamically Allocated Object

#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

More from this blog

Amit singh's blog

235 posts