You are on page 1of 27

C++ FUNCTIONS 2

BY MR. TARUS
Pointers
Variable which stores the address of another variable.

A variable whose value is the address of another variable.

Pointers are symbolic representation of addresses.

Pointer variables can be of type i.e, int, float, char, array, function, etc.

Pointers are user defined datatypes

Syntax for declaration:  int *ip; // pointer to an integer


return type *variable_name;  double *dp; // pointer to a double
int *ptr;  float *fp; // pointer to a float
char *c;  char *ch // pointer to character
int a = 5;
Advantages / uses of pointers
Reduces the code and improves the performance, it is used to retrieving strings,
trees, etc. and used with arrays, structures, and functions.

We can return multiple values from a function using the pointer.

It makes you able to access any memory location in the computer's memory.

Dynamic memory allocation


C++ language, we can dynamically allocate memory using malloc() and calloc()
functions

Arrays, Functions, and Structures


C++ language pointers are widely used in arrays, functions, and structures.
Examples of pointers in a program
//pointer program demo
#include<iostream>
using namespace std;
int main ()
{
int a = 20;
int *ptr;
cout<<" Address of a = : "<<&a<<endl;
cout<<"\nvalue at address = "<<*(&a)<<endl;
return 0;
}
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
cout << "Address stored in ip variable: "; // print the address stored in ip pointer
variable
cout << ip << endl;
cout << "Value of *ip variable: "; // access the value at the address available in
pointer
cout << *ip << endl;
return 0;
}
Pass by reference
Call/Pass by reference is the process where the original values are passed to the
corresponding function definition. Any changes made in the function definition
affects the actual parameters.
eg addition(int &a, int &b, int &c);

int addition(int *x, int *y, int *z)

Pass by reference uses the concept of Pointers:


// Pass by Reference int swap(int *x, int *y)
int swap(int *x, int *y); {
int main() int z;
{ z = *x;
int a=5, b=7;
*x = *y;
cout<<"\nOriginal values\n";
*y = z;
cout<<"\na = \t"<<a<<endl;
cout<<"\nValues in function defin\n";
cout<<"b = \t"<<b<<endl;
cout<<"\na = \t"<<*x<<endl;
swap(&a,&b);
cout<<"\nValue after interchange\n"; cout<<"b = \t"<<*y<<endl;
cout<<"\na = \t"<<a<<endl; return 0;
cout<<"b = \t"<<b; }
return 0;
}
Pointer concepts in C++
1. null pointer:
 C++ supports null pointer.
 A constant with a value of zero defined in several standard libraries
(iostream)
 Done at the time of variable declaration.
//nullpointer.cpp
int main () {
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
• 0, signals that the pointer is not intended to
return 0; point to an accessible memory location.
} • if a pointer contains the null (zero) value, it is
assumed to point to nothing.
Pointer concepts in C++ : pointerArithmetic.cpp
1. Pointer arithmetic:
•  Four arithmetic operators that can be used on pointers: ++, --, +, -
• Let ptr be an integer pointer pointing to address 1000. Then ptr++,
• points to loc 1004 cause each time ptr is incremented, it will point to the next integer.
• operation will move the pointer to next memory location without impacting actual value
at the memory location.
• If ptr points to a character whose address is 1000, then above operation will point to the
location 1001 because next character will be available at 1001.
Incrementing /Decrementing a Pointer for (int i = 0; i < MAX; i++/i--) {
cout << "Address of var[" << i << "] = ";
const int MAX = 3;
int main () {
cout << ptr << endl;
int var[MAX] = {10, 100, 200}; cout << "Value of var[" << i << "] = ";
int *ptr; cout << *ptr << endl;
ptr = var; // increm array address in pointer. ptr++ /ptr--; // point to the next location
//ptr = &var[MAX-1]; for decrem pointer }
Pointer concepts in C++: pointerComparrison.cpp
2. Pointer Comparisons
 Compared by using relational operators, such as ==, <, and >.
 Let p1 and p2 point to variables that are related to each other such as elements of
the same array, then p1 and p2 can be meaningfully compared.
int main () { while ( ptr <= &var[MAX - 1] ) {
int var[MAX] = {10, 100, 200}; cout << "Address of var[" << i << "] = ";
int *ptr; cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
// let us have address of the first cout << *ptr << endl;
element in pointer. // point to the previous location
ptr = var; ptr++;
int i = 0; i++; }
Pointer concepts in C++
2. Pointer Vs Arrays
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
ptr = var; // let us have array address in pointer.
for (int i = 0; i < MAX; i++) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
ptr++; // point to the next location
}
Difference between call by value and call by reference
Call/Pass by value Call/Pass by reference

 A copy of value is passed to the  An address of value is passed to the


function function

 Changes made inside the function is  Changes made inside the function is
not reflected on other functions reflected outside the function also

 Actual and formal arguments will be  Actual and formal arguments will be
created in different memory location created in same memory location
C++ Function Overriding:
 If derived class defines same function as defined in its base class, it is known as
function overriding

 It is used to achieve runtime polymorphism.

 It enables you to provide specific implementation of the function which is


already provided by its base class.

 overriding.cpp
class Animal {
public:
void eat(){
int main()
cout<<"Eating...";
{
}
Dog d;
};
d.eat();
class Dog: public Animal
return 0;
{
}
public:
void eat()
{
cout<<"Eating bread...";
} };
C++ virtual function
 A member function in the base class that you redefine in a derived class.
 Declared using the virtual keyword.
 Used to tell the compiler to perform dynamic linkage or late binding on the function.
 A 'virtual' is a keyword preceding the normal declaration of a function.
 When the function is made virtual, C++ determines which function is to be invoked
at the runtime based on the type of the object pointed by the base class pointer.
 There is a necessity to use the single pointer to refer to all the objects of the different
classes. So, we create the pointer to the base class that refers to all the derived
objects. But, when base class pointer contains the address of the derived class
object, always executes the base class function. This issue can only be resolved by
using the 'virtual' function.
 When you refer to a derived class object using a pointer or a reference to the base
class, you can call a virtual function for that object and execute the derived class’s
version of the function.
Pto…

 Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.

 They are mainly used to achieve Runtime polymorphism

 Functions are declared with a virtual keyword in base class.

 The resolving of function call is done at Run-time.


Rules of Virtual Function
 Virtual functions must be members of some class.
 Virtual functions cannot be static members.
 They are accessed through object pointers.
 They can be a friend of another class.
 A virtual function must be defined in the base class, even though it is not used.
 The prototypes of a virtual function of the base class and all the derived classes
must be identical. If the two functions with the same name but different
prototypes, C++ will consider them as the overloaded functions.
 We cannot have a virtual constructor, but we can have a virtual destructor
 Consider the situation when we don't use the virtual keyword.
class A {
int x=5;
int main()
public:
void display() {
{ A *a;
cout << "Value of x is : " <<x<<endl; B b;
}
a = &b;
};
class B: public A { a->display();
int y = 10; //b.display();
public: return 0;
void display()
}
{
cout << "Value of y is : " <<y<<endl;
}
}; Not virtual function demo program
Explanation

 *a is the base class pointer.

 The pointer can only access the base class members but not the members of the
derived class.

 Although C++ permits the base pointer to point to any object derived from the
base class, it cannot directly access the members of the derived class.

 Therefore, there is a need for virtual function which allows the base pointer to
access the members of the derived class.
C++ virtual function ; virtual1.cpp
class A {
public:
virtual void display() int main()
{ {
cout<<"Base class is invoked"; A *a; //pointer of base class
} B b; //object of derived class
};
a = &b;
class B : public A {
a->display();//Late Binding occurs
public:
void display()
}
{
cout <<"Derived Class is invoked";
}
};
Pure Virtual Function
 Not used for performing any task. It only serves as a placeholder.

 Function declared in the base class that has no definition relative to the base class.

 A class containing the pure virtual function cannot be used to declare the objects
of its own, such classes are known as abstract base classes.

 The main objective of the base class is to provide the traits to the derived classes
and to create the base pointer used for achieving the runtime polymorphism.

 Syntax:
virtual void display() = 0;  
class Base int main()
{
public: {
virtual void show() = 0;
Base *bptr; //Base b;
};
class Derived : public Base Derived d;
{
bptr = &d;
public:
void show() bptr->show();
{
return 0;
cout<<"Derived class is derived from the
base class."; }
}  Base class contains the pure virtual function (abstract base class).
};  We cannot create the object of the base class.
C++ Polymorphism

• The process of using a function or an operator for more than one purpose.
• Having many forms.
• Two types of
polymorphism in C++:
Two types:
Compile time polymo
Runtime polymo
 Compile time polymorphism:
Overloaded functions are invoked by matching the type and number of arguments.
This information is available at the compile time and, therefore, compiler selects
the appropriate function at the compile time.
achieved by function overloading and operator overloading which is also known as
static binding or early binding.

 Run time polymorphism:

achieved when the object's method is invoked at the run.

Achieved by method overriding (also known as dynamic binding or late binding).


C++ this Pointer

 this is a keyword that refers to the current instance of the class.

 Three main usage of this keyword in C++.


It can be used to pass current object as a parameter to another method.
It can be used to refer current class instance variable.
It can be used to declare indexers.

 thisPointer1.cpp
class Employee { int main()
public:
{
int id; //data member (also instance variable)
string name; //data member(also instance variable) Employee e1 =Employee(101,
float salary;
"Sonoo", 890000); //creating an
object of Employee
Employee(int id, string name, float salary)
{ Employee e2=Employee(102,
this->id = id; "Nakul", 59000); //creating an
this->name = name; object of Employee
this->salary = salary;
}
e1.display();
void display()
{ e2.display();
cout<<id<<" "<<name<<" "<<salary<<endl; return 0;
} }
};

You might also like