C++ Pointers to Classes

Introduction

Pointers to classes in C++ allow you to manipulate objects dynamically and efficiently. Using pointers to access and manage objects can provide greater flexibility, particularly when dealing with dynamic memory allocation, polymorphism, and passing objects to functions.

Defining and Using Pointers to Classes

Basic Example

You can define a pointer to a class and use it to access the class’s members using the arrow operator (->).

Example: Pointer to a Class

#include <iostream>
using namespace std;

// Define a class
class Person {
public:
    string name;
    int age;

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

int main() {
    // Create an object dynamically using a pointer
    Person* personPtr = new Person;

    // Access members using the pointer
    personPtr->name = "Alice";
    personPtr->age = 30;

    // Call member function using the pointer
    personPtr->display();

    // Deallocate memory
    delete personPtr;

    return 0;
}

Output

Name: Alice, Age: 30

Explanation

  • Person* personPtr = new Person; creates a new Person object dynamically and assigns its address to the pointer personPtr.
  • personPtr->name and personPtr->age access the object’s members using the arrow operator.
  • personPtr->display(); calls the member function using the pointer.
  • delete personPtr; deallocates the memory allocated for the object.

Dynamic Array of Objects Using Pointers

You can create an array of objects dynamically using pointers.

Example: Array of Objects

#include <iostream>
using namespace std;

// Define a class
class Person {
public:
    string name;
    int age;

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

int main() {
    int numPersons = 3;

    // Dynamically allocate memory for an array of objects
    Person* persons = new Person[numPersons];

    // Access and modify members of the array of objects
    for (int i = 0; i < numPersons; i++) {
        cout << "Enter name for person " << i + 1 << ": ";
        cin >> persons[i].name;
        cout << "Enter age for person " << i + 1 << ": ";
        cin >> persons[i].age;
    }

    // Call member function for each object in the array
    for (int i = 0; i < numPersons; i++) {
        persons[i].display();
    }

    // Deallocate memory
    delete[] persons;

    return 0;
}

Output

Enter name for person 1: Alice
Enter age for person 1: 30
Enter name for person 2: Bob
Enter age for person 2: 25
Enter name for person 3: Charlie
Enter age for person 3: 35
Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Charlie, Age: 35

Explanation

  • Person* persons = new Person[numPersons]; dynamically allocates memory for an array of Person objects.
  • The members of each object in the array are accessed and modified using the pointer.
  • The display member function is called for each object in the array.
  • delete[] persons; deallocates the memory allocated for the array of objects.

Passing Objects to Functions Using Pointers

You can pass objects to functions using pointers, which allows the function to modify the original object’s members.

Example: Passing Objects to Functions

#include <iostream>
using namespace std;

// Define a class
class Person {
public:
    string name;
    int age;

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

// Function to modify the object's members
void modifyPerson(Person* personPtr) {
    personPtr->name = "David";
    personPtr->age = 40;
}

int main() {
    // Create an object
    Person person = {"Alice", 30};

    // Pass the object to the function using a pointer
    modifyPerson(&person);

    // Print the modified members
    person.display();

    return 0;
}

Output

Name: David, Age: 40

Explanation

  • The modifyPerson function takes a pointer to a Person object as an argument.
  • The function modifies the object’s members using the pointer.
  • The modified members are printed in the main function.

Example Programs

Example 1: Managing a Collection of Dynamic Objects

#include <iostream>
using namespace std;

// Define a class
class Book {
public:
    string title;
    string author;

    void display() {
        cout << "Title: " << title << ", Author: " << author << endl;
    }
};

int main() {
    int numBooks;
    cout << "Enter the number of books: ";
    cin >> numBooks;

    // Dynamically allocate memory for an array of objects
    Book* books = new Book[numBooks];

    // Input book details
    for (int i = 0; i < numBooks; i++) {
        cout << "Enter title for book " << i + 1 << ": ";
        cin.ignore(); // To ignore newline character left in the buffer
        getline(cin, books[i].title);
        cout << "Enter author for book " << i + 1 << ": ";
        getline(cin, books[i].author);
    }

    // Display book details
    for (int i = 0; i < numBooks; i++) {
        books[i].display();
    }

    // Deallocate memory
    delete[] books;

    return 0;
}

Output

Enter the number of books: 2
Enter title for book 1: C++ Programming
Enter author for book 1: Bjarne Stroustrup
Enter title for book 2: Effective C++
Enter author for book 2: Scott Meyers
Title: C++ Programming, Author: Bjarne Stroustrup
Title: Effective C++, Author: Scott Meyers

Explanation

  • Book* books = new Book[numBooks]; dynamically allocates memory for an array of Book objects.
  • The user inputs the details of each book, which are stored in the array.
  • The details of each book are displayed using the display member function.
  • delete[] books; deallocates the memory allocated for the array of objects.

Example 2: Dynamic Object Creation and Member Function Calls

#include <iostream>
using namespace std;

// Define a class
class Car {
private:
    string brand;
    int year;

public:
    Car(string b, int y) : brand(b), year(y) {}

    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    // Create an object dynamically using a pointer
    Car* carPtr = new Car("Toyota", 2020);

    // Call member function using the pointer
    carPtr->display();

    // Deallocate memory
    delete carPtr;

    return 0;
}

Output

Brand: Toyota, Year: 2020

Explanation

  • Car* carPtr = new Car("Toyota", 2020); creates a new Car object dynamically and assigns its address to the pointer carPtr.
  • carPtr->display(); calls the member function using the pointer.
  • delete carPtr; deallocates the memory allocated for the object.

Conclusion

Pointers to classes in C++ allow for dynamic memory allocation and efficient management of objects. This chapter covered the basics of defining and using pointers to classes, creating dynamic arrays of objects, passing objects to functions using pointers, and managing collections of dynamic objects. Example programs demonstrated practical applications of pointers to classes, including modifying objects through pointers and dynamically creating objects. Understanding how to use pointers to classes effectively is essential for writing flexible and efficient C++ programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top