SlideShare a Scribd company logo
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.
Most read
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.
Most read
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
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

What's hot (20)

Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Operator overloading in C++
Operator  overloading in C++Operator  overloading in C++
Operator overloading in C++
BalajiGovindan5
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
This pointer
This pointerThis pointer
This pointer
Kamal Acharya
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
The Object Model
The Object Model  The Object Model
The Object Model
yndaravind
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
Mayank Jain
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Member Function in C++
Member Function in C++ Member Function in C++
Member Function in C++
NikitaKaur10
 
Operator overloading in C++
Operator  overloading in C++Operator  overloading in C++
Operator overloading in C++
BalajiGovindan5
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
ElangovanTechNotesET
 
The Object Model
The Object Model  The Object Model
The Object Model
yndaravind
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
Mayank Jain
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 

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

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
ANUSUYA S
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
Pointer
PointerPointer
Pointer
manish840
 
Pointers
PointersPointers
Pointers
Prof. Dr. K. Adisesha
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
Terry Yoast
 
Link list
Link listLink list
Link list
Malainine Zaid
 
Pointers_in_c.pptfffgfggdggffffrreeeggttr
Pointers_in_c.pptfffgfggdggffffrreeeggttrPointers_in_c.pptfffgfggdggffffrreeeggttr
Pointers_in_c.pptfffgfggdggffffrreeeggttr
MorfaSafi
 
C/C++ Pointers explanationwith different examples
C/C++ Pointers explanationwith different examplesC/C++ Pointers explanationwith different examples
C/C++ Pointers explanationwith different examples
ulhaq18
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
Data structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptxData structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
Pointers
PointersPointers
Pointers
sanya6900
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
Mysteriousexpert
 
polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.
UdayGumre
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
MuhammadAbubakar680442
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
ramya marichamy
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
Mauryasuraj98
 
Pointers
PointersPointers
Pointers
Nivetha Palanisamy
 
Savitch Ch 09
Savitch Ch 09Savitch Ch 09
Savitch Ch 09
Terry Yoast
 
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
ANUSUYA S
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
Terry Yoast
 
Pointers_in_c.pptfffgfggdggffffrreeeggttr
Pointers_in_c.pptfffgfggdggffffrreeeggttrPointers_in_c.pptfffgfggdggffffrreeeggttr
Pointers_in_c.pptfffgfggdggffffrreeeggttr
MorfaSafi
 
C/C++ Pointers explanationwith different examples
C/C++ Pointers explanationwith different examplesC/C++ Pointers explanationwith different examples
C/C++ Pointers explanationwith different examples
ulhaq18
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
Edward Chen
 
Data structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptxData structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
6be10b153306cc41e65403247a14a4dba5f9186aCHAPTER 2_POINTERS, VIRTUAL FUNCTIONS...
Mysteriousexpert
 
polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.polymorphism in c++ with Full Explanation.
polymorphism in c++ with Full Explanation.
UdayGumre
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
ramya marichamy
 
Ad

Recently uploaded (20)

Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Ad

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.