4
Most read
9
Most read
12
Most read
C++ (Programming Language)
Submitted By: T. Hari Tharshini
Pointer to Class & Object
Pointers
 Pointers are variables that store the
address of another variable. Instead of
holding actual data, they point to the
location where the data resides.
 To declare a pointer, you use the * operator.
For instance, to declare an integer pointer:
int *p;
 This tells the compiler that p is a pointer to
an integer. However, this pointer doesn’t yet
point to any address.
Initializing Pointers
 After declaration, it's crucial to initialize a
pointer before using it. An uninitialized
pointer can lead to undefined behavior.
You can initialize it with the address of a
variable:
int x = 10;
int *p = &x;
 Here, p now contains the address of x.
The & operator fetches the address of
the variable. It’s called reference
operator.
Dereferencing Pointers
 The process of retrieving the value
from the address a pointer is pointing
to is called dereferencing. To
dereference a pointer, use
the * operator again:
int y = *p; // y will be 10, as *p gives the
value stored at the address p is pointing
to
Pointer Types
 Each pointer in C++ has a specific
type: the type of data to which it
points. For example, an int pointer can
only point to an integer, a float pointer
can only point to a floating-point
number, and so forth.
Type Pointer Declaration
int int* p;
float float* f;
char char* c;
Common Errors With Pointers
 One common mistake is not initializing a
pointer before use. Always ensure a
pointer points to a valid location. Another
pitfall is going beyond the memory
bounds. This can corrupt data or crash
the program.
int arr[5];
int *p = arr; // Pointing to the start of
the array
*(p + 5) = 10; // Error! We’re
accessing memory beyond the array's
bounds
Pointer Arithmetic
 C++ allows arithmetic operations on
pointers. However, one must be
cautious while doing so to avoid
accessing unintended memory
locations.
int a = 5, b = 10;
int *ptr = &a;
ptr++; // Now ptr points to b
Class Pointers
 In C++, not only can you have pointers
to fundamental data types, but you
can also have pointers to classes.
These allow for more dynamic and
flexible object handling, especially
when dealing with polymorphism and
dynamic memory allocation.
Declaring Class Pointers
 When you have a class, declaring a
pointer to it is similar to how you
declare pointers to basic data types.
Given a class named Car, you would
declare a pointer to it as follows:
class Car { // ... class definition ... };
Car *ptrCar;
 After this, ptrCar can point to an
instance (object) of the Car class.
Initializing And Using Class
Pointers
 To make your pointer useful, you should
make it point to an actual object. You can
either point it to an existing object or
allocate memory dynamically.
Car myCar;
ptrCar = &myCar; // Pointing to an existing
object
Car *dynamicCar = new Car(); //
Dynamically allocating memory for a Car
object and pointing to it
 When accessing members (both data
members and member functions) of
the class through the pointer, use the
arrow (->) operator:
ptrCar->startEngine(); // Calls the
startEngine() method of the object
pointed to by ptrCar
Dynamic Memory And Class
Pointers
 One of the key utilities of class pointers is in
dynamic memory allocation. When creating
objects at runtime based on program needs,
using new and delete becomes essential.
Car *dynamicArray = new Car[10]; // Allocates
memory for an array of 10 Car objects
delete[] dynamicArray; // Frees up the allocated
memory once done
 Always remember to free up memory after
use to prevent memory leaks.
Polymorphism And Class
Pointers
 One of the strengths of class pointers lies
in polymorphism. By having a base class
pointer point to a derived class object, you can
achieve runtime polymorphism.
class Base {};
class Derived : public Base {};
Base *bPtr = new Derived(); // Base pointer
pointing to derived class object
 This feature enables more dynamic behavior,
especially with overridden functions and virtual
functions in C++.
Declaring And Initializing
Class Pointers
 Working with objects in C++ often
requires understanding how to declare
and initialize pointers to those objects.
Handling class pointers correctly can
enable dynamic memory management
and more flexible object interactions.
Declaration Of Class Pointers
 A class pointer declaration follows a
similar syntax as pointers to basic data
types. Let's say we have a class
named Robot. A pointer to this class
would be:
class Robot {
// ... class definition ...
};
Robot *ptrRobot; // Declaration of pointer
to Robot class
Initializing With Existing
Objects
 Often, you might want a pointer to
reference an existing object. This can
be done using the address-of operator
(&):
Robot r2d2;
ptrRobot = &r2d2; // ptrRobot now
points to r2d2
Dynamic Memory Allocation
 For more dynamic applications, C++ allows
for on-the-fly memory allocation using
the new keyword. This is especially useful
when the number or size of objects needed
is unknown at compile time.
Robot *dynRobot = new Robot(); // Allocates
memory and initializes a new Robot object
 Always remember, for every new, there
should be a corresponding delete to free up
the allocated memory:
delete dynRobot; // Frees up the memory
Pointers To Class Arrays
 You can also declare and initialize pointers
to arrays of class objects. This is useful for
creating collections of objects dynamically:
Robot *robotArray = new Robot[5]; //
Creates an array of 5 Robot objects
// Accessing members of the array
robotArray[2].activate(); // Activates the third
robot in the array
 Again, remember to free the memory:
delete[] robotArray; // Deletes the entire
array
The Arrow Operator
 The arrow operator (->) is your primary tool
for accessing members of a class via a
pointer. This operator is a combination of the
dereference (*) operator and the dot (.)
operator.
 Given a class Vehicle:
class Vehicle {
public: void honk() {
// Honking logic
}
};
Vehicle *ptrVehicle = new Vehicle();
ptrVehicle->honk(); // Using the arrow operator
to access the honk function
Accessing Data Members
 Just as with member functions, data
members of a class are also accessed
using the arrow operator when
working with pointers.
class Vehicle {
public: int speed;
};
Vehicle *ptrVehicle = new Vehicle();
ptrVehicle->speed = 60; // Setting the
speed data member via pointer
Dereferencing And The Dot
Operator
 Though the arrow operator is more
common and direct, you can also
dereference the pointer and use the dot
operator to access class members:
(*ptrVehicle).speed = 50; // Dereferencing
the pointer and then using the dot operator
 This method is less common because it's
more verbose, but understanding it
underscores the concept that the arrow
operator is just a shorthand for this
process.
Accessing Array Elements
Through Pointers
 If you have a pointer to an array of objects,
you can combine pointer arithmetic with
member access:
Vehicle *fleet = new Vehicle[10];
(fleet + 3)->speed = 70; // Accessing the
speed of the fourth vehicle in the array
 It's essential to remember the precedence
of operators here. The arrow operator will
act before the addition, so using
parentheses ensures the correct behavior.

More Related Content

PDF
Constructors and Destructors
PPTX
Access specifier
PPTX
Static Data Members and Member Functions
PDF
Function overloading ppt
PPTX
Association agggregation and composition
PPTX
Abstract class and Interface
PDF
Friend function in c++
PPTX
Dynamic memory allocation in c++
Constructors and Destructors
Access specifier
Static Data Members and Member Functions
Function overloading ppt
Association agggregation and composition
Abstract class and Interface
Friend function in c++
Dynamic memory allocation in c++

What's hot (20)

PPTX
sSCOPE RESOLUTION OPERATOR.pptx
PPTX
[OOP - Lec 19] Static Member Functions
PDF
Classes and objects
PPTX
Pointers in C Programming
PPTX
PPTX
Applets in java
PPS
String and string buffer
PPTX
class and objects
PPT
Java interfaces
PPTX
classes and objects in C++
PPTX
Fundamentals of Python Programming
PPTX
Interface in java
PPT
Operators in C++
PPTX
Inheritance in java
PPT
Friends function and_classes
PDF
Differences between c and c++
PPTX
Virtual base class
PPT
Literals,variables,datatype in C#
PPT
Class and object in C++
sSCOPE RESOLUTION OPERATOR.pptx
[OOP - Lec 19] Static Member Functions
Classes and objects
Pointers in C Programming
Applets in java
String and string buffer
class and objects
Java interfaces
classes and objects in C++
Fundamentals of Python Programming
Interface in java
Operators in C++
Inheritance in java
Friends function and_classes
Differences between c and c++
Virtual base class
Literals,variables,datatype in C#
Class and object in C++
Ad

Similar to C++ Class & object pointer in c++ programming language (20)

PPTX
Pointers,virtual functions and polymorphism cpp
PPTX
Pointers, virtual function and polymorphism
PPT
pointers, virtual functions and polymorphisms in c++ || in cpp
DOCX
C questions
PPTX
pointers in c programming - example programs
DOCX
New microsoft office word document (2)
PDF
CS225_Prelecture_Notes 2nd
PPTX
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
PPTX
pointer, virtual function and polymorphism
PPTX
OOC MODULE1.pptx
PPT
C++ Interview Questions
PPTX
Programming in C sesion 2
PDF
C,c++ interview q&a
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
PPTX
Structured Languages
PPTX
C++ tutorial assignment - 23MTS5730.pptx
PDF
polymorphism in c++ with Full Explanation.
PPT
Virtual Function and Polymorphism.ppt
PPTX
Computer science ( Structures In C ) Ppt
PPTX
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
Pointers,virtual functions and polymorphism cpp
Pointers, virtual function and polymorphism
pointers, virtual functions and polymorphisms in c++ || in cpp
C questions
pointers in c programming - example programs
New microsoft office word document (2)
CS225_Prelecture_Notes 2nd
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
pointer, virtual function and polymorphism
OOC MODULE1.pptx
C++ Interview Questions
Programming in C sesion 2
C,c++ interview q&a
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Structured Languages
C++ tutorial assignment - 23MTS5730.pptx
polymorphism in c++ with Full Explanation.
Virtual Function and Polymorphism.ppt
Computer science ( Structures In C ) Ppt
BBACA-SEM-III-Datastructure-PPT(0) for third semestetr
Ad

Recently uploaded (20)

PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 2).pdf
PDF
Journal of Dental Science - UDMY (2021).pdf
PDF
semiconductor packaging in vlsi design fab
PDF
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
PDF
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
Hazard Identification & Risk Assessment .pdf
PDF
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
advance database management system book.pdf
PPTX
Education and Perspectives of Education.pptx
PPTX
Module on health assessment of CHN. pptx
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PDF
HVAC Specification 2024 according to central public works department
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 2).pdf
Journal of Dental Science - UDMY (2021).pdf
semiconductor packaging in vlsi design fab
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
Share_Module_2_Power_conflict_and_negotiation.pptx
Hazard Identification & Risk Assessment .pdf
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
Paper A Mock Exam 9_ Attempt review.pdf.
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
advance database management system book.pdf
Education and Perspectives of Education.pptx
Module on health assessment of CHN. pptx
Uderstanding digital marketing and marketing stratergie for engaging the digi...
HVAC Specification 2024 according to central public works department
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx

C++ Class & object pointer in c++ programming language

  • 1. C++ (Programming Language) Submitted By: T. Hari Tharshini Pointer to Class & Object
  • 2. Pointers  Pointers are variables that store the address of another variable. Instead of holding actual data, they point to the location where the data resides.  To declare a pointer, you use the * operator. For instance, to declare an integer pointer: int *p;  This tells the compiler that p is a pointer to an integer. However, this pointer doesn’t yet point to any address.
  • 3. Initializing Pointers  After declaration, it's crucial to initialize a pointer before using it. An uninitialized pointer can lead to undefined behavior. You can initialize it with the address of a variable: int x = 10; int *p = &x;  Here, p now contains the address of x. The & operator fetches the address of the variable. It’s called reference operator.
  • 4. Dereferencing Pointers  The process of retrieving the value from the address a pointer is pointing to is called dereferencing. To dereference a pointer, use the * operator again: int y = *p; // y will be 10, as *p gives the value stored at the address p is pointing to
  • 5. Pointer Types  Each pointer in C++ has a specific type: the type of data to which it points. For example, an int pointer can only point to an integer, a float pointer can only point to a floating-point number, and so forth. Type Pointer Declaration int int* p; float float* f; char char* c;
  • 6. Common Errors With Pointers  One common mistake is not initializing a pointer before use. Always ensure a pointer points to a valid location. Another pitfall is going beyond the memory bounds. This can corrupt data or crash the program. int arr[5]; int *p = arr; // Pointing to the start of the array *(p + 5) = 10; // Error! We’re accessing memory beyond the array's bounds
  • 7. Pointer Arithmetic  C++ allows arithmetic operations on pointers. However, one must be cautious while doing so to avoid accessing unintended memory locations. int a = 5, b = 10; int *ptr = &a; ptr++; // Now ptr points to b
  • 8. Class Pointers  In C++, not only can you have pointers to fundamental data types, but you can also have pointers to classes. These allow for more dynamic and flexible object handling, especially when dealing with polymorphism and dynamic memory allocation.
  • 9. Declaring Class Pointers  When you have a class, declaring a pointer to it is similar to how you declare pointers to basic data types. Given a class named Car, you would declare a pointer to it as follows: class Car { // ... class definition ... }; Car *ptrCar;  After this, ptrCar can point to an instance (object) of the Car class.
  • 10. Initializing And Using Class Pointers  To make your pointer useful, you should make it point to an actual object. You can either point it to an existing object or allocate memory dynamically. Car myCar; ptrCar = &myCar; // Pointing to an existing object Car *dynamicCar = new Car(); // Dynamically allocating memory for a Car object and pointing to it
  • 11.  When accessing members (both data members and member functions) of the class through the pointer, use the arrow (->) operator: ptrCar->startEngine(); // Calls the startEngine() method of the object pointed to by ptrCar
  • 12. Dynamic Memory And Class Pointers  One of the key utilities of class pointers is in dynamic memory allocation. When creating objects at runtime based on program needs, using new and delete becomes essential. Car *dynamicArray = new Car[10]; // Allocates memory for an array of 10 Car objects delete[] dynamicArray; // Frees up the allocated memory once done  Always remember to free up memory after use to prevent memory leaks.
  • 13. Polymorphism And Class Pointers  One of the strengths of class pointers lies in polymorphism. By having a base class pointer point to a derived class object, you can achieve runtime polymorphism. class Base {}; class Derived : public Base {}; Base *bPtr = new Derived(); // Base pointer pointing to derived class object  This feature enables more dynamic behavior, especially with overridden functions and virtual functions in C++.
  • 14. Declaring And Initializing Class Pointers  Working with objects in C++ often requires understanding how to declare and initialize pointers to those objects. Handling class pointers correctly can enable dynamic memory management and more flexible object interactions.
  • 15. Declaration Of Class Pointers  A class pointer declaration follows a similar syntax as pointers to basic data types. Let's say we have a class named Robot. A pointer to this class would be: class Robot { // ... class definition ... }; Robot *ptrRobot; // Declaration of pointer to Robot class
  • 16. Initializing With Existing Objects  Often, you might want a pointer to reference an existing object. This can be done using the address-of operator (&): Robot r2d2; ptrRobot = &r2d2; // ptrRobot now points to r2d2
  • 17. Dynamic Memory Allocation  For more dynamic applications, C++ allows for on-the-fly memory allocation using the new keyword. This is especially useful when the number or size of objects needed is unknown at compile time. Robot *dynRobot = new Robot(); // Allocates memory and initializes a new Robot object  Always remember, for every new, there should be a corresponding delete to free up the allocated memory: delete dynRobot; // Frees up the memory
  • 18. Pointers To Class Arrays  You can also declare and initialize pointers to arrays of class objects. This is useful for creating collections of objects dynamically: Robot *robotArray = new Robot[5]; // Creates an array of 5 Robot objects // Accessing members of the array robotArray[2].activate(); // Activates the third robot in the array  Again, remember to free the memory: delete[] robotArray; // Deletes the entire array
  • 19. The Arrow Operator  The arrow operator (->) is your primary tool for accessing members of a class via a pointer. This operator is a combination of the dereference (*) operator and the dot (.) operator.  Given a class Vehicle: class Vehicle { public: void honk() { // Honking logic } }; Vehicle *ptrVehicle = new Vehicle(); ptrVehicle->honk(); // Using the arrow operator to access the honk function
  • 20. Accessing Data Members  Just as with member functions, data members of a class are also accessed using the arrow operator when working with pointers. class Vehicle { public: int speed; }; Vehicle *ptrVehicle = new Vehicle(); ptrVehicle->speed = 60; // Setting the speed data member via pointer
  • 21. Dereferencing And The Dot Operator  Though the arrow operator is more common and direct, you can also dereference the pointer and use the dot operator to access class members: (*ptrVehicle).speed = 50; // Dereferencing the pointer and then using the dot operator  This method is less common because it's more verbose, but understanding it underscores the concept that the arrow operator is just a shorthand for this process.
  • 22. Accessing Array Elements Through Pointers  If you have a pointer to an array of objects, you can combine pointer arithmetic with member access: Vehicle *fleet = new Vehicle[10]; (fleet + 3)->speed = 70; // Accessing the speed of the fourth vehicle in the array  It's essential to remember the precedence of operators here. The arrow operator will act before the addition, so using parentheses ensures the correct behavior.