SlideShare a Scribd company logo
1 of 22
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

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

Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&aKumaran K
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Abu Saleh
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptishan743441
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)nirajmandaliya
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxssuser688516
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IAjit Nayak
 

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

C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
C,c++ interview q&a
C,c++ interview q&aC,c++ interview q&a
C,c++ interview q&a
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Pointers
PointersPointers
Pointers
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Dynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptxDynamic Memory Allocation.pptx
Dynamic Memory Allocation.pptx
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
 
Presentation
PresentationPresentation
Presentation
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 

Recently uploaded

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

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.