10. Virtual & Friend function

Virtual Function in C++

A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. 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.

  • 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 for Virtual Functions

  1. Virtual functions cannot be static and also cannot be a friend function of another class.
  2. Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
  3. The prototype of virtual functions should be same in base as well as derived class.
  4. They are always defined in base class and overridden in derived class. It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used.
  5. A class may have virtual destructor but it cannot have a virtual constructor.

Pure Virtual Functions in C++

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration.

Similarities between virtual function and pure virtual function

  1. These are the concepts of Run-time polymorphism.
  2. Prototype i.e. Declaration of both the functions remains the same throughout the program.
  3. These functions can’t be global or static.
 Syntax:-
      virtual void f() = 0;

Friend class and function in C++

Friend Class 
A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other class. 
For example a Linked List class may be allowed to access private members of Node.

filter_none
edit
play_arrow

brightness_4
class Node { 
private: 
    int key; 
    Node* next; 
    /* Other members of Node Class */
    // Now class  LinkedList can 
    // access private members of Node 
    friend class LinkedList; 
}; 

Friend Function Like friend class, a friend function can be given special grant to access private and protected members. 
A friend function can be:
a) A method of another class
b) A global function

Following are some important points about friend functions and classes:

1) Friends should be used only for limited purpose. too many functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in object-oriented programming.

2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically.

3) Friendship is not inherited (See this for more details)

4) The concept of friends is not there in Java.

Pointer to Objects

A Variable That Holds an Address value is called a Pointer variable or simply pointer. We already discussed about pointer that's point to Simple data types likes int, char, float etc. So similar to these type of data type, Objects can also have an address, so there is also a pointer that can point to the address of an Object, This Pointer is Known asThis Pointer.

This Pointer

In C++ programming, this is a keyword that refers to the current instance of the class. 

There can be 3 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.
Example:-
#include <iostream>

using namespace std;
class Car{
private:
int Number_of_wheels;
int Number_of_passengers;
public:
void getinfo(int x, int y){
this->Number_of_wheels = x;
this->Number_of_passengers = y;
}        
void showinfo(){
cout<<"Number of Wheels = "<<Number_of_wheels<<"n";
cout<<"Number of Passengers = "<<Number_of_passengers<<"n";
cout<<"Address of the current object is = "<<this<<"n"; } }; int main() { Car car; Car *ptr; ptr=&car; ptr->getinfo(4,5);
ptr->showinfo();
Car car2;
car2.getinfo(6,8);
car2.showinfo();
return 0;
}

Output:-
          Number of Wheels = 4    
          Number of Passengers = 5            
          Address of the current object is =0x7ffdbac81740   
          Number of Wheels = 6                      
          Number of Passengers = 8      
          Address of the current object is = 0x7ffdbac81748

Pointers to Derived class

Pointers can not only be used to refer to the base class but they can also be used to point at a derived class object. For example, if class Car inherits from class Vehicles, a pointer of type Vehicles can also be used to point towards an object of type Car.

Vehicles *ptr;
Vehicles vehicles;
Car car;
ptr = &vehicles;
ptr = & car;

The only catch here is that if we are using a base class pointer to point towards the derived class object we will be able to access only base class methods which are inherited by the derived class object. We can not access the members of the derived class using the base class pointer.

 If a member of the class Car has the same name as one of the members of class Vehicles then, in that case, the pointer will access the base class member.

Early binding and Late binding in C++

Binding refers to the process of converting identifiers (such as variable and performance names) into addresses. Binding is done for each variable and functions. For functions, it means that matching the call with the right function definition by the compiler. It takes place either at compile time or at runtime.


1). Early Binding (compile-time time polymorphism) 

As the name indicates, compiler (or linker) directly associate an address to the function call. It replaces the call with a machine language instruction that tells the mainframe to leap to the address of the function.

By default early binding happens in C++. Late binding (discussed below) is achieved with the help of virtual keyword)

Example:-
#include<iostream> 
using namespace std; 

class Base 

public: 
    void show() { cout<<" In Base \n"; } 
}; 
    class Derived: public Base 

public: 
    void show() { cout<<"In Derived \n"; } 
}; 
    
int main(void) 

    Base *bp = new Derived; 
   // The function call decided at  
    // compile time (compiler sees type 
    // of pointer and calls base class 

    bp->show();   
   return 0; 


Output:-
 In Base

2). Late Binding : (Run time polymorphism) 

In this, the compiler adds code that identifies the kind of object at runtime then matches the call with the right function definition (Refer this for details). This can be achieved by declaring a virtual function.

Example:-
#include<iostream> 
using namespace std; 
class Base 

public: 
    virtual void show() { cout<<" In Base \n"; } 
}; 
    class Derived: public Base 

public: 
    void show() { cout<<"In Derived \n"; } 
}; 
int main(void) 

    Base *bp = new Derived; 
    bp->show();  // RUN-TIME POLYMORPHISM 
    return 0; 

Output:-
       In Derived

Post a Comment

0 Comments