0% found this document useful (0 votes)
71 views22 pages

C++ UNIT 4 Notes

This document covers the concept of pointers in C++, including their declaration, usage with classes, and dynamic memory management. It explains the 'this' pointer, pointers to base and derived classes, and the creation and initialization of arrays and arrays of classes. Additionally, it discusses memory models, the new and delete operators for dynamic object management, and provides code examples for better understanding.

Uploaded by

fowmila j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views22 pages

C++ UNIT 4 Notes

This document covers the concept of pointers in C++, including their declaration, usage with classes, and dynamic memory management. It explains the 'this' pointer, pointers to base and derived classes, and the creation and initialization of arrays and arrays of classes. Additionally, it discusses memory models, the new and delete operators for dynamic object management, and provides code examples for better understanding.

Uploaded by

fowmila j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT- 4

Pointers–Declaration–Pointer to Class, Object–this pointer–Pointers to derived classes and


Base classes– Arrays–Characteristics–array of classes–Memory models–new and delete
operators–Dynamic object–Binding, Polymorphism and Virtual Functions.

POINTERS

 A pointer is a special variable that holds the memory address of another variable, rather than
storing a direct value itself.
 When we access a pointer directly, we get the address it holds not the actual data stored at that
location.

#include <iostream>
using namespace std;
int main()
{
int var = 10;

// declare pointer and store address of x


int* ptr = &var;

// print value and address


cout << "Value of x: " << var << endl;
cout << "Address of x: " << &var << endl;
cout << "Value stored in pointer ptr: " << ptr << endl;
cout << "Value pointed to by ptr: " << *ptr << endl;

return 0;
}
Output
Value of x: 10
Address of x: 0x7fffa0757dd4
Value stored in pointer ptr: 0x7fffa0757dd4
Value pointed to by ptr: 10
 nt* ptr; declares a pointer to an integer.
 ptr = &x; stores the address of variable x in the pointer ptr.
 *ptr is called the dereference operator. It gives us access to the value stored at the memory
address ptr is pointing to.
 So, ptr holds the address of x, and *ptr gives the value of x by accessing that address.

CREATE POINTER
 A pointer can be declared in the same way as any other variable but with an asterisk symbol
(*) as shown

Datatype * name
 Here, datatype is the type of data that the pointer is pointing to, and name is the name
assigned to the pointer. The * symbol is also called dereference operator. operator.
Example:
int* ptr;
 In the above statement, we create a pointer ptr that can store the address of an integer data. It
is pronounced as "Pointer to Integer" or "Integer Pointer"

Assign Address

The addressof operator (&) determines the address of any variable in C++. This address can be
assigned to the pointer variable to initialize it.

Example:
int val = 22;
int* ptr = &val;
In the above statement, pointer ptr store the address of variable val using address-of operator (&). The
pointer and the variable should be of same type, otherwise type mismatch error occurs.
Dereferencing
The process of accessing the value present at the memory address pointed by the pointer is
called dereferencing. This is done with the help of dereferencing operator as shown:
#include <iostream>
using namespace std;
int main() {
int var = 10;

// Store the address of


// var variable
int* ptr = &var;

// Access value using (*)


// operator
cout << *ptr;
return 0;
}
Output
10
POINTERS TO CLASS
 A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access
members of a pointer to a class you use the member access operator -> operator, just as you
do with pointers to structures.
 A pointer to a class is a variable that stores the memory address of an object, allowing you to
access and manipulate the object indirectly.
 Using a class pointer is common for dynamic memory management, polymorphism, and
implementing complex data structures.

Declaring and initializing a class pointer


To declare a pointer to a class, you use the asterisk (*) operator, just like with a pointer to a primitive
data type. Before using the pointer, you must initialize it to point to a valid object.
ClassName* pointerName;
#include <iostream>
class Dog {
public:
std::string name;
int age;
void bark() {
std::cout << name << " says: Woof!" << std::endl;
}
};
int main() {
// 1. Declare a class object on the stack
Dog myDog;
myDog.name = "Fido";
myDog.age = 5;
// 2. Declare a pointer to the class
Dog* dogPtr;
// 3. Assign the memory address of the object to the pointer
dogPtr = &myDog;
// The pointer 'dogPtr' now points to the 'myDog' object.
}
Initialization:
A pointer to an object can be initialized in a few ways: Pointing to an existing object.
ClassName obj;
ClassName *ptr = &obj; // ptr now holds the address of obj
Dynamically allocating an object using new.
ClassName *ptr = new ClassName(); // Allocates an object on the heap and ptr points to it
Accessing Members:
When using a pointer to an object, you use the arrow operator -> to access its public data
members and member functions.
ptr->dataMember;
ptr->memberFunction();
class MyClass {
public:
int value;
void display() {
// Code to display value
}
};
int main() {
MyClass obj; // Create an object
MyClass *ptr = &obj; // Create a pointer and point it to obj
ptr->value = 10; // Access data member using arrow operator
ptr->display(); // Call member function using arrow operator
MyClass *dynamicObj = new MyClass(); // Dynamically allocate an object
dynamicObj->value = 20;
dynamicObj->display();
delete dynamicObj; // Deallocate memory for dynamically created object
return 0;
}
'THIS' POINTER IN C++

In C++, 'this' pointer is an implicit pointer available inside all non-static member
function, and it always points to the current object that called the function. This pointer is
internally used by methods to access the other members.
#include <iostream>
using namespace std;
// Class demonstrating use of 'this' pointer
class Student {
private:
string name;
int age;
public:
// Constructor with parameters having the same name
Student(string name, int age) {
// 'this' is used to distinguish between class members and constructor parameters
this->name = name;
this->age = age;
}
// Member function using 'this'
void introduce() {
cout << "Hi, I am " << this->name
<< " and I am " << this->age << " years old." << endl;
}
// Returning current object using 'this'
Student& olderBy(int years) {
this->age += years;
return *this;
}
};
int main() {
Student s("Alice", 20);
// Display initial introduction
s.introduce();
// Increase age and reintroduce
s.olderBy(2).introduce();
return 0;
}

Output

Hi, I am Alice and I am 20 years old.


Hi, I am Alice and I am 22 years old.

POINTERS TO BASE CLASS AND DERIVED CLASS


A pointer is a data type that stores the address of other data types. Pointers can be used for
base objects as well as objects of derived classes. A pointer to the object of the derived class and a
pointer to the object of the base class are type-compatible (may be used in different ways).

Base Class: The general class from which others inherit.


Derived Class: A class that inherits from the base.
Pointer to Base Class: Can point to an object of the base class or any class derived from it.
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() { // Make it virtual for polymorphism
cout << "Base class show()" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class show()" << endl;
}
};
int main() {
Base* bptr;
Derived d;
bptr = &d; // Base class pointer points to derived object
bptr->show(); // Calls Derived::show() because of virtual
return 0;
}
OUTPUT
Derived class show()

ARRAYS
An array is a collection of elements of the same type placed in contiguous memory locations.
It allows you to store multiple values under a single name and access them using an index.
#include <iostream>
using namespace std;
int main() {
// declaring and initializing an array of size 5
int arr[5] = {2, 4, 8, 12, 16};
// printing array elements
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output
2 4 8 12 16
Explanation:
 int arr[5] declares an array of 5 integers.
 The elements are initialized with {2, 4, 8, 12, 16}.
 The for loop is used to iterate over the array and print each element.
 Array indices in C++ start from 0, so arr[0] refers to the first element, and arr[4] refers to the
last one in this case.
Create an Array
We can create/declare an array by simply specifying the data type first and then the name of the array
with its size inside [] square brackets(better known as array subscript operator ).

Syntax
data_type array_name [size]
This statement will create an array with name array_name that can store size elements of
given data_type. Once the array is declared, its size cannot be changed.

Example:int arr[5];

Initialize the Array


Initialization means assigning initial values to array elements. We can initialize the array with values
enclosed in curly braces '{}' are assigned to the array.

For example:
int arr[5] = {2, 4, 8, 12, 16};
These values will be assigned sequentially. It means that the first element (index 0) will be 10, second
will be 20, and so on.

The number of values in the list cannot be more than the size of the array. But they can be less
that the size. This is called partial initialization.

int arr[5] = {2, 4, 8};


Access Array Elements
Elements of an array can be accessed by their position (called index) in the sequence. In C++, indexes
of an array starts from 0 instead of 1.

We just have to pass this index inside the [] square brackets with the array name as shown:

array_name[index];

CHARACTERISTICS OF ARRAYS
 All the elements of an array of the same name and they are differentiated from one another
with the help of elements number.
 The element number in an array is the most important factor in calling each element.
 Any particular element of an array can be modified without disturbing the other element.
 Any element of an array can be assigned to another ordinary variable (or) array variable of its
type
 The array elements are stored in continuous memory locations, the amount of storage required
for the elements depends on its type and size
 Total bytes=sizeof( data type)*sizeof(array)

ARRAY OF CLASSES
An array is a collection of similar data type in the same way it is also possible to define array
of classes.
Here array is a class type array of class object can be declared as follows:
class student
{
char sname[20];
student s[10];
int sno[10];
char sadr[20];
}
Example
#include<iostream.h>
#include<conio.h>
Class student
{
Char sname[20];
Char grade;
int sno;
Public:
void get();
void display()
};
void student::get()
{
cin>>sname;
cin>>sno;
cin>>grade;
}
void student::display()
{
cout<<<<>n;
for(i=1;i<=n;i++)
{
S[i].get();
}
for(i=1;i<=n;i++)
{
S[i] display();
}}

MEMORY MODELS
The different types of memory models used in C++ are as follows :
Tiny
• The tiny model is absolutely premium all four segment registers(CS,DS,SS,ES) are initialized with
same address and all addressing is accomplished using 16-bits total memory capacity is 64 kb.
• The code data and stack must fit with in the same 64kb segment
• Programme are executed quickly is this model is selected.
Small
• All code should fit in a single 64kb segment.
• All pointers are 16bit in length execution speed is same as single model.
• This model is used for average size programs near pointers are always used.
Medium
• All data fit in a single 64kb segment.
• The code is allowed to use multiple segments
. • All jumps and calls require 32bits address
. • In this model access to data is passed program execution is slowwith their model.
• Far pointers are used for code.
Compact
• All code fit in 64kb segment to the data can use multiple segment all pointers to data and 32bits.
• But jumps and calls used 16bits slow action to data and quick code execution will be observed this
model.
• For pointers are preferred for data.
Large
• Both code and data allowed to multiple segment. • All pointers are 32bits code execute is slow.
• This model is preferred for very big programs.
• For pointers are used for both code and data.
6. Huge
• Both code and data are allowed to use multiple segments
• Every pointers is 32bits in length cod execution is the slowest.
• The huge model permits multiple data segments 1MB code segments and 64kb for stack.
Segment and offset address
• Every address has to parts segment and offset these parts are defined using two macrosdefind in
header file.
• FP-SEG()-this macros is used to obtained segment address.
• FP-OFF() – this macros is used to obtained offset address.
The new and delete operators
• C++ provide new and delete operators can be used for crating and destroying the object.

NEW OPERATOR
The new operator allocates memory of specified type and returns the starting address to the
pointers memory variable.
If it’s fails to allocate its returns null value.
Syntax
Pointer memory variable=new data type
Example
a= new int;
int *a = new int[50];
*a = new int[3];

DELETE OPERATOR
• The delete operator frees the memory location allocated the operators.
Syntax
Delete pointer variable name;
Delete [element size] pointer variable name;
Example
Delete a;
Delete[50] a;

Size of operator
• The sizeof operator is used to returns the size of your variable bytes.
Syntax
sizeof (variable name);
Example
• Cout<<sizeof(a);

Few points regarding: new and delete operators are


 The new operator not only creates an object but also allocates memory.
 The new operator allocates correct amount of memory from the heap that also called a free
store.
 The object created and memory allocated using new operator should be deleted by the delete
operator.
 The delete operator not only destroys the object but also returns the allocated memory.
 The new operator creates an object and its remains in the memory until it is released using
delete operator.
 If we sent a null pointers to delete operator it is secure using delete to zero(0) has no result.
 The statement delete x does not destroy the pointer x.
 It destroy the object.
 If the object created is not deleted it occupy the unnecessarily
 It is a good habit to destroy the object and release the system resources.

#include <iostream>
int main() {
// Dynamically allocate memory for an integer
int* number = new int;
// Assign a value
*number = 42;
// Print the value
std::cout << "The number is: " << *number << std::endl;
// Deallocate the memory
delete number;
return 0;
}

OUTPUT
The number is: 42

DYNAMIC OBJECT
 In C++, the objects can be created at run-time. C++ supports two operators new and delete to
perform memory allocation and de-allocation.
 These types of objects are called dynamic objects.
 The new operator is used to create objects dynamically and the delete operator is used to
delete objects dynamically.
 The dynamic objects can be created with the help of pointers.

Syntax
ClassName *ptr_obj; // pointer to object
ptr_obj = new ClassName // Dynamic object creation
delete ptr_obj; //Delete Object
#include<iostream>
using namespace std;

// Class definition
class Test
{
// Data members
int a, b;
public:

// Constructor to initialize
// data members of class
Test()
{
cout << "Constructor is called" <<
endl;
a = 1;
b = 2;
};

// Destructor
~Test()
{
cout << "Destructor is called" <<
endl;
}

// Function to print values


// of data members
void show()
{
cout << "a = " <<
a << endl;
cout << "b = " <<
b << endl;
}
};

// Driver code
int main()
{
// pointer to object
Test *ptr;

// dynamic object creation


ptr = new Test;

// Accessing member through


// pointer to object
ptr->show();

// Destroying object dynamically


delete ptr;
return 0;
} dynamically
// Delete object dynamically

Reference to Dynamic Objects

The address of dynamic objects returned by the new operator can be dereferenced and a reference to
them can be created.

Syntax
ClassName &RefObj = * (new ClassName);
// C++ program to implement
// Reference to dynamic objects
#include<iostream>
#include<string.h>
using namespace std;

class student{

private:
int roll_no;
char name[20];

public:
void setdata(int roll_no_in,
char name_in[20])
{
roll_no = roll_no_in;
strcpy(name, name_in);
}

void outdata()
{
cout << "Roll No is: " <<
roll_no << endl;
cout << "Name: " << name <<
endl;
}
};

// Driver code
int main()
{
// Reference to dynamic object
student &s1 = *(new student);
s1.setdata(1, "Ajay");
s1.outdata();

// Reference to dynamic object


student &s2 = *(new student);
s2.setdata(2, "Aman");
s2.outdata();
student &s3 = *(new student);
s3.setdata(3, "Akshay");

// Reference to static object


student &s4 = s3;
s3.outdata();
s4.outdata();
return 0;
}
Output:
Roll No is: 1
Name: Ajay
Roll No is: 2
Name: Aman
Roll No is: 3
Name: Akshay
Roll No is: 3
Name: Akshay

BINDING

In C++, binding refers to the process of connecting a function call to the function's actual code
(definition). There are two main types of binding:

🔹 1. Static Binding (Early Binding)

The function call is resolved at compile time.


This usually happens with:

Non-virtual functions
Function overloading
Operator overloading
Templates
It is faster since the compiler knows exactly what to call.
class Animal {
public:
void speak() {
std::cout << "Animal speaks\n";
}
};

int main() {
Animal a;
a.speak(); // Statically bound
}

2. Dynamic Binding (Late Binding)


The function call is resolved at runtime.

Happens when a virtual function is called through a base class pointer or reference.

Requires use of the virtual keyword in base class.


class Animal {
public:
virtual void speak() {
std::cout << "Animal speaks\n";
}
};

class Dog : public Animal {


public:
void speak() override {
std::cout << "Dog barks\n";
}
};

int main() {
Animal* a = new Dog();
a->speak(); // Dynamically bound (Dog::speak is called)
delete a;
}

Polymorphism in C++
Polymorphism means "many forms".
In C++, polymorphism allows objects of different classes to be treated as objects of a common base
class, typically through inheritance.
The most common use of polymorphism is to call virtual functions through base class pointers
or references.
Type When it's resolved Mechanism

Compile-time (Static) At compile time Function overloading, operator overloading, templates

Run-time (Dynamic) At runtime Virtual functions and inheritance


Compile-Time Polymorphism (Static)
➤ Function Overloading
Same function name, different parameters.
class Printer {
public:
void print(int i) {
std::cout << "Integer: " << i << "\n";
}
void print(double d) {
std::cout << "Double: " << d << "\n";
}
};
Operator Overloading
Define custom behavior for operators.
class Complex {
public:
int real, imag;
Complex(int r, int i): real(r), imag(i) {}
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
};

2. Run-Time Polymorphism (Dynamic)

Achieved via virtual functions and pointers or references to base class.


🔹 Example:
class Animal {
public:
virtual void speak() {
std::cout << "Animal speaks\n";
}
};
class Dog : public Animal {
public:
void speak() override {
std::cout << "Dog barks\n";
}
};

void makeItSpeak(Animal* a) {
a->speak(); // Calls Dog::speak() if passed a Dog*
}

int main() {
Dog d;
makeItSpeak(&d); // Output: Dog barks
}

VIRTUAL FUNCTIONS
A virtual function is a member function that is declared within a base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Virtual functions enable runtime polymorphism, calling the correct function via a base class pointer or
reference.
Virtual functions are mainly related to inheritance, allowing derived classes to provide their own
implementation of base class functions.
When a derived class object is deleted through a base class pointer, a virtual destructor in the base
class ensures that both the derived and base class destructors are called, safely releasing all resources.
The virtual destructor is declared using the keyword virtual in the base class.
If a class has any virtual functions, its destructor should also be declared virtual. This is crucial for
proper cleanup in polymorphic scenarios, especially when dealing with dynamic memory and
inheritance.
Pure virtual function :-
• The member function of the class is rarely used for doing any operation.
• Such function are called do-nothing functions, dummy function or pure virtual function.
• The pure virtual function are always virtual function.
• There are defined with null body after declaration of pure virtual function in a class. The becomes
abstract class.
• It cannot be used for declare any object.
The pure function can be declared as follows:
Syntax • virtual void display()=0;
• A pure virtual function declared in base class cannot be used for any operations.
• The class containing pure virtual function cannot be used declared object.
• Such class are known as abstract class (or) pure abstract class.
• The class is derived from pure abstract classes are required to redeclared pure virtual function
. • All other derived classes witout pure virtual function are called concreate classes
. • These classes can be used to create objects.

You might also like