what does virtual and pure virtual function means in C++ and in java(abstract)

                 Virtual functions

  • Actually before starting this concept i would like to draw your attention on the term polymorphism that is what polymorphism stands for... Polymorphism means one name many forms in it we have function overloading.
  • Function overriding is a different concept often people make mistakes in it that what does function overloading and funtion overriding means actually we need these two concepts in mind at the first sight then we would go further defining the virtual functions and pure virtual functions in C++ and in java.
  • so lets understand what is function overloading here as we defined in the polymorphism that one name many forms to be very specific i would like to say one name many implementations.
  • suppose we take a simple example ,take the function of area so declare the function named area at the first... area is the general name , but many implimentations are possible of it such as area of circle,area of triangle, area of square,area of rectangle etc....!!
  • Now all have their main heading as area that is the function area but have different arguments for circle we might say it has radius so in bracket we might have argument as only one that is int area(int r),for triangle we might have the area such triangle we have the area as half * base into altitude so we can define its fuction as float area(float base float altitude)likewise we have for rectangle that is float area(int length float breadth). 
  • As we have seen that the main name of the function is the area and in that we have different arguments some have one some have two as well as their types that is when we pass an argument their type should match and third one is the return type which should match so the factors included in the function overloading with which we may distinguish between the the area as different functions are
  1. Number of argument lists
  2. type of arguments 
  3. return type
  • mainly these are the three factors that we must keep in mind so this all functions as discussed earlier might work based on the argument which the user or programmer sends at the time of function calling .

                      Efficient programming

  • calls are.... area( 3 ) so has only one argument that is the integer so decission is taken that this call is for the area fuction of the circle look above we defined in the body we can write return statement as return 3.14*r*r. 
  • now we have mentioned the return type integer and take one variable as an Lvalue to store the integer so the calling statement might be like this such as int a = area( 3 ) , the called function will return at the calling statement and at the left we have kept an int variable to store the ans later on we can print that ans or directly we can keep this call statement in the print statement so no need to take an extra variable by this  one can say that its efficient as they have kept memory unused that is they have saved the memory by keeping in mind these thing so its good convention of programming.
  • But what when we want to use that value again in the program for some reson so at that time we need an extra variable to store the return value again ahead in the program.

  • so these were some tips for good programming specially with concern to overloading as we use mostly the return statement concept in this topic 

so we completed about function overloading and i hope now u might have the clear meaning about the function overloading as we can differentiate the one fuction by the above three factors and at the time of calling we can provide the argument according to which it could identify.

  • Now moving to our next concept and the important one to understand the virtual as well as the pure virtual functions in C++ and in Java so now Function overriding.
  • First of all what is the meaning of overriding...?
  • That we have to clear first we say to override means to ride more than expected as we know that only one calling statement can call one function at a time but if we keep another calling statament in the defination that is in the body of that called function that justifies the meaning overriding for example we say that we called a function named show() in the body of show where we defined we write calling statement of another function such as verify().actually what happens is we wrote the calling statement of just one function but in the body as we kept the another calling statement it would also execute it.
  • So by calling one function we are able to execute two of them this becomes the actual meaning of overriding but this concept is useful to just understand and keep a side in mind.
  • Now comes the actual meaning of overriding the second meaning of it that as in overloading we have the three parameters function parameter list, type of parameter,and the return type.
  • But in overriding we have the same number of parameter same type and same return type of the function return type dosent affect much here.
  • one question arrises that how would the compiler identify when everything is same we have a solution .
  • for that i would like to take an example 
lets us take three classes say abc , pqr and xyz and overload the method in it...

class abc
{
public:
void show();//for virtual just ad keyword virtual here as virtual void show();
{
cout<<"this is the base class";
}
};
class xyz:public abc
{
public:
void show();
{
cout<<"this is drived class xyz of abc";
}
};
class pqr:public abc
void show()
{
cout<<"this is derived class pqr of abc";
}
};
Above example which i wrote is just presented to clear the concept of overloading not the complete program....

Now here by seeing the above example we could estimate that the overloaded function is the show function then whenever the needs arise by creating the object of the last derived class pqr then which method would be called that becomes the big question.....

  • Firstly its a general convention to create the object of the lastly derived class as it has the all inherited fatures of the above two classes so its easy to access all the members in above eg we have taken the small concept so it will not be effective but i m talking on the prograames on the large pupuse in mncs and colleges,schools database it affects a lot there.
  • Now comming back to our topic that how would the compiler know that we wrote the calling statement show() than show of class abc ,class xyz or class pqr as we have same show in all the classes.
  • For that keep in mind remember with which class object u have called the method show().
  • As i said take the last derived classe's object so we declare an object say pqr 01 now 01.show().
  • Now what happens actually is everytime the method of the last derived class will be only called at each time that is pqr and we also have taken the object of class pqr so each and every time the method of the derived class will only be called as per convention.
  • What to do to call the method of the base class, the same method which we have defined that is the show() method.
  • we have inheritance in C++ such as.....
  • Simple,multiple,multilevel,hierarchical,hybrid. so there is possibilities that we have number of base class and derived class.
  • So at any time we can call the method of any class just the work we haave to do is to write the class name besides the method. 
  • For class abc if we want to call the method we have to write abc::show(),for xyz we write xyz::show() and normally for the derived class of whose object which we have created will be called definetly if we didnt write the class name for a specific call.
  • The second method to identify is the simple method just declare the object of the class you want to and use dot(.) operator to call the method.
  • Here in both cases it becomes the direct way for the compiler to identify that which mthod will be called even we are also able to identify which method will be called just by seeing the program at the compile time.
  • Now the third method is by taking the pointer of the base class,This is the method in which we will make the use of the keyword virtual.
Now starting the concept of virtual keyword........
  • As we have seen we said to declare the base class pointer our base class was class abc.so abc *ptr.
  • Now declaring the object of the two derived class xyz and pqr say xyz p1 and pqr p2.
  • Now we assign these object in the refrence that is the pointer variable of base class ptr=&p1.
  • Now calling that method as ptr->show(). 
  • Now this would call the method of derived class as the object of derived class is called as we gave the object of the derived class in the refrence of the base class.
  • Note for pointing the object we can only take the refrence of the base class the reason for it will be in the upcomming post.
  • Just now we focus in the present post.
An example by using the virtual keyword is as follows


class Base
{
public:
virtual void show()
{
cout << "Base class";
}
};
{
class Derived:public Base
cout << "Derived Class";
public:
void show()
{ } }
Base* b; //Base class pointer
int main() {
Derived d; //Derived class object
b = &d;
b->show(); //Late Binding Ocuurs
}


  • Here the output will be Derived class 

  • On using Virtual keyword with Base class's function, Late Binding takes place and the derived version of function will be called, because base class pointer pointes to Derived class object.
  • At compile time as we have the refrence variable of base class surely its function will be called this was the talk at compile time so the problem is not resolved.

Important points to exercise .......

  • Some might say that firstly the compiler will go to find the function in base class yes than truncate the function from the base class again this arguement is valid we can the the compiler will call the function of the immediate derived class if it finds there.
  • Now what when we want to call about the function of the base class unfortunately we truncated it now again we define there then again that will only be called every time at compile time.
  • So came the existence of the keyword virtual place this word at the function defined in the base class.
  • Now how this virtual keyword will work for that we have to understand the word virtual.
  • Simple english we mean virtual means not real so at initial stage people learn that when the control comes to the function of the base it hides it so it can move forword this is for understanding at the initial level.
  • But the true mechanism is it points the refrence of the derived object stored in it and calls transfers the control over that function and vice versa.
  • lets take an example our base class is abc now we took the pointer variable of it and stored the refrence of the derived class as many as we have say we have stored the refrence of the derived class xyz at first sight so as soon as the control will go to the base class and checks whose refrence is stored in it if its own refrence is stored than its most welcome and allows to enter.
  • And if not then dosent allow the control to enter there checks refrence of which derived is present in it and transfers the control over there say if it is of xyz than the function of xyz will be called if of pqr than vice versa.
  • in simple terms it orders the control by checking the refrence and shows the real destination.

  • This was the simple mechanism behind the keyword virtual.

Now comming towards the pure virtual function.


What is a pure virtual function?
  • A pure virtual function is a function that has the notation "= 0" in the declaration of that function. Why we would want a pure virtual function and what a pure virtual function looks like is explored in more detail below.

Here is a simple example of what a pure virtual function in C++ would look like:

Simple Example of a pure virtual function in C++


class SomeClass {
public:
   virtual void pure_virtual() = 0;  // a pure virtual function
   // note that there is no function body    
};

The pure specifier.....


The "= 0" portion of a pure virtual function is also known as the pure specifier, because it’s what makes a pure virtual function “pure”. Although the pure specifier appended to the end   of the virtual function definition may look like the function is     being assigned a value of 0, that is not true. The notation "= 0"   is just there to indicate that the virtual function is a pure       virtual function, and that the function has no body or definition.   Also note that we named the function “pure_virtual” –   that was     just to make the example easier to understand, but it certainly     does not mean that all pure virtual functions must have that name   since they can have any name they want.
Can a pure virtual function have an implementation?

The quick answer to that question is yes! A pure virtual function can have an implementation in C++ – which is something that even many veteran C++ developers do not know. So, using the SomeClass class from our example above, we can have the following code:


class SomeClass {
public:
   virtual void pure_virtual() = 0;  // a pure virtual function
   // note that there is no function body    
};

/*This is an implementation of the pure_virtual function
    which is declared as a pure virtual function.
    This is perfectly legal:
*/
void SomeClass::pure_virtual() {
    cout<<"This is a test"<<endl;
}


Why would you want a pure virtual function to have an implementation?
  • It is actually pretty rare to see a pure virtual function with an implementation in real-world code, but having that implementation may be desirable when you think that classes which derive from the base class may need some sort of default behavior for the pure virtual function. So, for example, if we have a class that derives from our SomeClass class above, we can write some code like this – where the derived class actually makes a call to the pure virtual function implementation that is inherited: 
A class with a pure virtual function is called an abstract class

Any class that has at least one pure virtual function is called an abstract class. This means that in our example above, the SomeClass class is an abstract class. An abstract class cannot have an instance of itself created.




Pure virtual functions in Java

In Java, pure virtual methods are declared using the abstract keyword – note that C++ does not use the keyword “abstract” as part of the language itself, although C++ does have abstract classes – any class with at least one virtual function is considered to be abstract. So, in Java abstract methods are the equivalent of pure virtual functions in C++. In Java, an abstract method cannot have a body, just like a pure virtual function in C++. A class containing abstract methods must itself be declared abstract. But, an abstract class is not necessarilly required to have any abstract methods. An abstract class cannot be instantiated.

When should pure virtual functions be used in C++?

In C++, a regular, "non-pure" virtual function provides a definition, which means that the class in which that virtual function is defined does not need to be declared abstract. You would want to create a pure virtual function when it doesn’t make sense to provide a definition for a virtual function in the base class itself, within the context of inheritance.

An example of when pure virtual functions are necessary

For example, let’s say that you have a base class called Figure. The Figure class has a function called draw. And, other classes like Circle and Square derive from the Figure class. In the Figure class, it doesn’t make sense to actually provide a definition for the draw function, because of the simple and obvious fact that a “Figure” has no specific shape. It is simply meant to act as a base class. Of course, in the Circle and Square classes it would be obvious what should happen in the draw function – they should just draw out either a Circle or Square (respectively) on the page. But, in the Figure class it makes no sense to provide a definition for the draw function. And this is exactly when a pure virtual function should be used – the draw function in the Figure class should be a pure virtual function.





So this was all about virtual and pure virtual keyword concept given my 100 percent to explain the inner concept of course we have the concept of vtable ,vptr but this explaination is enough and will clear all doubts and will make easy to remember some internal guideliness i have provided as efficient programming that would help you and points to exercise that would make you think a little higher .



hope u might enjoy while reading and give your valuable feedbacks..
any kind of improvement needed to write the post.....













Comments

Popular posts from this blog

Navigation in Vaadin.

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Drag and drop items from one Grid to another