Module II

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

POINTERS

A variable which stores the address of another variable is called a pointer. Pointers
are said to "point to" the variable whose address they store.

An interesting property of pointers is that they can be used to access the variable
they point to directly. This is done by preceding the pointer name with the
dereference operator (*). The operator itself can be read as "value pointed to by".

An array can always be implicitly converted to the pointer of the proper type
USING POINTERS IN C++

• we define a pointer variables


• assign the address of a variable to a pointer
• finally access the value at the address available in the pointer variable.
• This is done by using unary operator * that returns the value of the variable located at the
address specified by its operand.
Concept Description

C++ supports null pointer, which is a constant with a value of zero defined in several
C++ Null Pointers
standard libraries.

There are four arithmetic operators that can be used on pointers: ++, --, +, - . Pointers
may be compared by using relational operators, such as ==, <, and >. If p1 and p2
C++ pointer arithmetic
point to variables that are related to each other, such as elements of the same array,
then p1 and p2 can be meaningfully compared.

C++ pointers vs arrays There is a close relationship between pointers and arrays.

C++ array of pointers You can define arrays to hold a number of pointers.

C++ pointer to pointer C++ allows you to have pointer on a pointer and so on.

Passing an argument by reference or by address both enable the passed argument to


Passing pointers to functions
be changed in the calling function by the called function.

C++ allows a function to return a pointer to local variable, static variable and
Return pointer from functions
dynamically allocated memory as well.
Address-of operator (&)
The address of a variable can be obtained by preceding the name of a variable with an
ampersand sign (&), known as address-of operator.
• The reference and dereference operators are thus complementary:
• & is the address-of operator, and can be read simply as "address of"
• * is the dereference operator, and can be read as "value pointed to by"
REFERENCES IN C++

• References are like constant pointers that are automatically dereferenced. It is a new name
given to an existing storage. Accessing the reference is actually accessing that storage.
• int main()
• { int y=10;
• int &r = y; // r is a reference to int y
• cout << r;
• }
• Output : 10
• There is no need to use the * to dereference a reference variable.
DIFFERENCE BETWEEN REFERENCE AND POINTER

• References • Pointers
• Reference must be initialized when it is created. • Pointers can be initialized any time.
• Once initialized, we cannot reinitialize a • Pointers can be reinitialized any number of
reference. time.
• You can never have a NULL reference. • Pointers can be NULL.
• Reference is automatically dereferenced. • * is used to dereference a pointer.
REFERENCES IN FUNCTIONS
References are generally used for function argument lists and function return values, just like
pointers.
Rules for using Reference in Functions
1. When we use reference in argument list, we must keep in mind that any change to the
reference inside the function will cause change to the original argument outside the function.

2. When we return a reference from a function, you should see that whatever the
reference is connected to shouldn't go out of scope when function ends. Either make that
global or static
int* first (int* x)
{ (*x++);
return x; // SAFE, x is outside this scope
}
int& second (int& x)
{ x++;
return x; // SAFE, x is outside this scope
}
int& third ()
{ int q;
return q; // ERROR, scope of q ends here
}
int& fourth ()
{ static int x;
return x; // SAFE, x is static, hence lives till the end.
}

int main()
{
int a=0;
first(&a); // UGLY and explicit
second(a); // CLEAN and hidden
}
• We have four different functions in the above program.
• first() takes a pointer as argument and returns a pointer, it will work fine. The returning pointer
points to variable declared outside first(), hence it will be valid even after the first() ends.

• Similarly, second() will also work fine. The returning reference is connected to valid storage, that is
int a in this case.

• But in case of third(), we declare a variable q inside the function and try to return a reference
connected to it. But as soon as function third() ends, the local variable q is destroyed, hence nothing is
returned.

• To remedify above problem, we make x as static in function fourth(), giving it a lifetime till main()
ends, hence now a reference connected to x will be valid when returned.
DYNAMIC MEMORY
MANAGEMENT
• Memory in your C++ program is divided into two parts:
• The stack: All variables declared inside the function will take up memory from the stack.
• The heap: This is unused memory of the program and can be used to allocate the memory
dynamically when program runs.

• memory can be allocate at run time within the heap for the variable of a given type using a
special operator in C++ which returns the address of the space allocated. This operator is
called new operator.
• If dynamically allocated memory is no more required, the delete operator is used to de-
allocates memory previously allocated by new operator.
NEW AND DELETE OPERATORS
There is following generic syntax to use new operator to allocate memory dynamically for any data-type.
new data-type;

data-type could be any built-in data type including an array or any user defined data types include class or
structure

The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to
check if new operator is returning NULL pointer

The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The
main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is
prime purpose of C++.
To dynamically allocate memory for array:

char* pvalue = NULL; // Pointer initialized with null


pvalue = new char[20]; // Request memory for the variable

To remove the array:


delete [] pvalue; // Delete array pointed to by pvalue

multi-dimensional array as follows:


double** pvalue = NULL; // Pointer initialized with null
pvalue = new double [3][4]; // Allocate memory for a 3x4 array

The syntax to release the memory for multi-dimensional array remains:


delete [] pvalue; // Delete array pointed to by pvalue
POINTERS TO OBJECTS
• Members accessed to
POINTERS TO OBJECT MEMBERS
class Data
• Pointers can be used to point to class's Member { public:
functions. int f (float) { return 1; }
};
• Syntax :
• return_type (class_name::*ptr_name) int (Data::*fp1) (float) = &Data::f; // Declaration and
(argument_type) = &class_name::function_name ; assignment
int (Data::*fp2) (float); // Only Declaration

int main(0
{
fp2 = &Data::f; // Assignment inside main()
}
Pointers to class members
Just like pointers to normal variables and functions, we can have pointers to class member functions and member variables.
Defining a pointer of class type
We can define pointer of class type, which can be used to point to class objects.
class Simple
{
public:
int a;
};

int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;

cout << obj.a;


cout << ptr->a; // Accessing member with pointer
}
Here you can see that we have declared a pointer of class type which points to class's object. We can access data members and member functions using
pointer name with arrow -> symbol.
THIS POINTER
• Every object in C++ has access to its own address through “this” pointer.
• this pointer is an implicit parameter to all member functions.
• inside a member function, this may be used to refer to the invoking object.
• this pointer stores the address of the class instance, to enable pointer access of the members
to the member functions of the class.
OPERATOR OVERLOADING
• Overloading unary and binary operators
• redefine or overload most of the built-in operators available in C++.
• Overloaded operators are functions with special names the keyword operator followed by
the symbol for the operator being defined. Like any other function, an overloaded operator
has a return type and a parameter list.
Overloadable/Non-overloadableOperators: Following is the list of operators, which can not
be overloaded:
Following is the list of operators which can be overloaded:
::
+ -*/%^ .*
&|~!,= .
< > <= >= ++ -- ?:
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; } // Add Cents + Cents
friend Cents operator+(const Cents &c1, const Cents &c2); // note: this function is not a member
function!
int GetCents() { return m_nCents; }
};
Cents operator+(const Cents &c1, const Cents &c2) // use the Cents constructor and operator+
(int, int)
{
return Cents(c1.m_nCents + c2.m_nCents);
}
int main()
{
Cents cCents1(6);
Cents cCents2(8);
Cents cCentsSum = cCents1 + cCents2;
std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl;

return 0;
• Type conversion: Between objects and basic types and between objects of different classes
INHERITANCE

• Inheritance is the capability of one class to acquire properties and characteristics from
another class. The class whose properties are inherited by other class is called the
Parent or Base or Super class. And, the class which inherits properties of other class is
called Child or Derived or Sub class.
• Inheritance makes the code reusable. When we inherit an existing class, all its
methods and fields become available in the new class, hence code is reused.
Purpose of Inheritance
1. Code Reusability
2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Basic Syntax of Inheritance
• class Subclass_name : access_mode Superclass_name
• While defining a subclass like this, the super class must be already defined or atleast
declared before the subclass declaration.
• Access Mode is used to specify, the mode in which the properties of superclass will be
inherited into subclass, public, privtate or protected.
Inheritance Visibility Mode
Depending on Access modifier used while inheritance, the availability of class members of
Super class in the sub class changes. It can either be private, protected or public.
Public Inheritance
This is the most used inheritance mode. In this the protected member of super class
becomes protected members of sub class and public becomes public.
class Subclass : public Superclass
Private Inheritance
In private mode, the protected and public members of super class become private members
of derived class.
class Subclass : Superclass // By default its private inheritance
Protected Inheritance
In protected mode, the public and protected members of Super class becomes protected
members of Sub class.
class subclass : protected Superclass
• Overriding base class members
• Abstract classes
• Constructors and destructors in derived classes
#include <iostream> int main(void)
// Derived class
{
using namespace std;
class Rectangle: public Shape
Rectangle Rect;
{
// Base class public:
class Shape Rect.setWidth(5);
{ int getArea()
Rect.setHeight(7);
public: {
void setWidth(int w)
return (width * height);
{ // Print the area of the object.
width = w; }
cout << "Total area: " <<
} };
void setHeight(int h) Rect.getArea() << endl;
{
height = h;
}
return 0;
protected: }
int width;
int height;
TYPES OF INHERITANCE
Single Inheritance
One derived class inherits from only one base class. It is the most simplest form of
Inheritance.
Multiple Inheritance
A single derived class may inherit from two or more than two base classes.
Hierarchical Inheritance
Multiple derived classes inherits from a single base class.
Multilevel Inheritance
The derived class inherits from a class, which in turn inherits from some other class.
The Super class for one, is sub class for the other.
Hybrid (Virtual) Inheritance
Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.
VIRTUAL FUNCTIONS, VIRTUAL
BASE CLASS

• Overriding of functions:
• Virtual Function is a function in base class, which is overrided in the derived class, and
which tells the compiler to perform Late Binding on this function.
• Virtual Keyword is used to make a member function of the base class Virtual.
ABSTRACT CLASS

• Abstract Class is a class which contains atleast one Pure Virtual function in it.
• Abstract classes are used to provide an Interface for its sub classes.
• Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become
abstract class.
• Object can not be created
Characteristics of Abstract Class
• Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be created.
• Abstract class can have normal functions and variables along with a pure virtual function.
• Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
• Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become Abstract too.
Pure Virtual Functions
• Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends with = 0. Here is the
syntax for a pure virtual function,
• virtual void f() = 0;
• Order of Constructor Call
• Base class constructors are always called in the derived class constructors. Whenever you
create derived class object, first the base class default constructor is executed and then the
derived class's constructor finishes execution.
Points to Remember1. Whether derived class's default constructor is called or parameterised is
called, base class's default constructor is always called inside them.

• 2. To call base class's parameterised constructor inside derived class's parameterised
constructo, we must mention it explicitly while declaring derived class's parameterized
constructor.
BASE CLASS DEFAULT CONSTRUCTOR IN
DERIVED CLASS CONSTRUCTORS
class Base class Derived : public Base
{ int y;
{ int x; public:
public: Derived() { cout << "Derived default constructor"; }
Derived(int i) { cout << "Derived parameterized
Base() { cout << "Base default constructor";
constructor"; }
} };
}; int main()
{
Base b;
Derived d1;
Derived d2(10);
}
• Why is Base class Constructor called inside Derived class ?
• Constructors have a special job of initializing the object properly. A Derived class constructor has access only to its own class members, but a Derived class object also have
inherited property of Base class, and only base class constructor can properly initialize base class members. Hence all the constructors are called, else object wouldn't be
constructed properly.
• ________________________________________
• Constructor call in Multiple Inheritance
• Its almost the same, all the Base class's constructors are called inside derived class's constructor, in the same order in which they are inherited.
• class A : public B, public C ;
• In this case, first class B constructor will be executed, then class C constructor and then class A constructor.
• Upcasting in C++
• Upcasting is using the Super class's reference or pointer to refer to a Sub class's object. Or we can say that, the act of converting a Sub class's reference or pointer into its Super
class's reference or pointer is called Upcasting.

• class Super
• { int x;
• public:
• void funBase() { cout << "Super function"; }
• };

• class Sub : public Super
• { int y;
• };

• int main()
• {
• Super* ptr; // Super class pointer
• Sub obj;
• ptr = &obj;

• Super &ref; // Super class's reference
• ref=obj;
• }
• The opposite of Upcasting is Downcasting, in which we convert Super class's reference or pointer into derived class's reference or pointer. We will study more about
Downcasting later
• ________________________________________
• Functions that are never Inherited
• Constructors and Destructors are never inherited and hence never overrided.
• Also, assignment operator = is never inherited. It can be overloaded but can't be inherited by sub class.
• Hybrid Inheritance and Virtual Class
• In Multiple Inheritance, the derived class inherits from more than one base class. Hence, in Multiple Inheritance there are a lot chances of ambiguity.
• class A
• { void show(); };

• class B:public A {};

• class C:public A {};

• class D:public B, public C {};

• int main()
• {
• D obj;
• obj.show();
• }
• In this case both class B and C inherits function show() from class A. Hence class D has two inherited copies of function show(). In main() function when we call function show(), then
ambiguity arises, because compiler doesn't know which show() function to call. Hence we use Virtual keyword while inheriting class.
• class B : virtual public A {};

• class C : virtual public A {};

• class D : public B, public C {};
• Now by adding virtual keyword, we tell compiler to call any one out of the two show() funtions.
• ________________________________________
• Hybrid Inheritance and Constructor call
• As we all know that whenever a derived class object is instantiated, the base class constructor is always called. But in case of Hybrid Inheritance, as
discussed in above example, if we create an instance of class D, then following constructors will be called :
• before class D's constructor, constructors of its super classes will be called, hence constructors of class B, class C and class A will be called.
• when constructors of class B and class C are called, they will again make a call to their super class's constructor.
• This will result in multiple calls to the constructor of class A, which is undesirable. As there is a single instance of virtual base class which is shared by
multiple classes that inherit from it, hence the constructor of the base class is only called once by the constructor of concrete class, which in our case is
class D.
• If there is any call for initializing the constructor of class A in class B or class C, while creating object of class D, all such calls will be skipped.
• Polymorphism
• Polymorphism means having multiple forms of one thing. In inheritance, polymorphism is done, by method overriding, when both super and sub class
have member function with same declaration bu different definition.
FILE PROCESSING
• Opening and closing files
• File pointers
• Filestream functions
• Creating and processing text and binary files

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy