Pointers in C++
Pointers in C++
( The phrase means that the behavior of the function (what the
function does when it is called) will change depending on the
actual type of the object that the base class pointer is pointing
to.)
Pointer Basics
In C++, pointers allow us to work with memory directly by storing
memory addresses.
● Declaring a pointer:
To declare a pointer, use the * symbol.
int x = 10;
Dereferencing a pointer:
#include <iostream>
int main() {
int x = 10;
// Pointer to x
// Printing address of x
return 0;
OUTPUT:
Value of x: 10
Pointers in Object-Oriented Programming
CODE:
#include <iostream>
class Box {
public:
double length;
double width;
double height;
Box(double l, double w, double h) : length(l), width(w), height(h)
{}
double volume() {
};
int main() {
cout << "Volume of the box: " << ptr->volume() << endl;
return 0;
Explanation:
OUTPUT:
Volume of the box: 30
CODE:
#include <iostream>
class Animal {
public:
};
public:
}
};
public:
};
int main() {
Dog dog;
Cat cat;
ptr = &cat;
return 0;
}
Explanation:
OUTPUT:
Dog barks!
Cat meows!
CODE:
#include <iostream>
class Vehicle {
public:
};
public:
};
int main() {
Car car;
vehiclePtr = &car;
return 0;
}
Explanation:
OUTPUT:
This is a car.