#Abstract classes & Pure Virtual functions in C++:
#Virtual/abstract Functions in C++:
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation(no body), we only declare it.
Virtual Function is a function in base class, which is overrided in the derived/sub 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.
A pure virtual function is declared by assigning 0 in declaration.
virtual returnType functionName(){ //partial virtual function
//body
}
OR
virtual returnType functionName() = 0; //Pure Virtaul Function
Ex:
virtual void draw(){
// partial
}
virtual void show()=0; // pure virtual
#abstract class:
----------------
A Class is a abstract class which contains atleast one Pure/partial virtual function is present is called as abstract Class.
Abstract classes are used to provide an Interface for its sub classes.
Sub-Classes inheriting an abstract class must provide definition(body) to the pure/partial virtual function, otherwise they will also become abstract class.
Ex:
// abstract class
class Demo{ //super class
int id;
public:
//function declaration
virtual void function1()=0; //pure virtual function
virtual void function2(){
//partial body definition
}
int get(){
return 123;
}
};
class subClass:public Demo{
public :
void scf1(){
//body of subclass function 1
}
//function overriding //polymorphism //late binding
void function1(){
//full body
}
void function2(){
//full body
}
};
Characteristics of abstract Class:
----------------------------------
Abstract class cannot be instantiated(object creation is not allowed), but programmer can create pointers and refrences of abstract class type.
normal functions and variables along with a pure virtual function can be present in abstract class.
Purporse: abstract classe are mainly used for Upcasting, so that its derived classes can use its interface.
Sub-Classes inheriting a abstract Class must implement(define the body of function) all pure/partial virtual functions, or else sub-classes also will become abstract too.
in some situation implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class.
Ex:
Late Binding in C++ :
---------------------
In Late Binding function call is resolved at runtime. Hence, now compiler determines the type of object at runtime, and then binds the function call. Late Binding is also called Dynamic Binding or Runtime Binding.
Programmatic Example:
------------------------