I do not know why but I feel so “C++” today (This is the first time I am using C++ as a verb haha) and hence this knowledge share… :)
If you are a C++ programmer, you must know that it is not advisable to overload Virtual Functions even though the compiler will not complain.
… But why?
Look at the below sample code:
#include
using std::cout;
class Base {
public:
virtual void foo(int f) {
cout << f;
}
virtual void foo(double f) {
cout << f;
}
};
class Derived : public Base {
public:
void foo(int f) {
cout << f;
}
};
int main() {
Derived *d = new Derived;
Base *b = d;
cout << "Calling Base foo(double) through Base\n";
b->foo(3.14); // Base Class foo(double) is called
cout << "Calling Base foo(double) through Derived\n";
d->foo(3.14);//Derived Class foo(int) is called
delete b;
}
THiNK 1: What will happen if you try to overload Pure Virtual Functions in the Derived Class? Will my below code compile? Try it :)
#include
using namespace std;
class base
{
public:
base();
virtual void foo()=0; //Pure virtual function
};
class Derived : public Base
{
public:
void foo(int f) //Pure virtual function overloaded
{cout << f;}
};
int main()
{
Derived *dObj = new Derived();
Base *bObj = dObj;
dObj->foo(2); //What will happen?
bObj->foo(2); //What will happen?
return 0;
}
NOTE: While all pure virtual functions MUST NOT have a function body, Pure Virtual Destructor MUST have! Also, Pure Virtual Destructors NEED NOT be overridden in the derived class. As a proof, the below code will compile and link fine…
class AbstractBase {
public:
virtual ~AbstractBase() = 0; //Pure Virtual Destructor and hence AbstractBase is an Abstract Class
};
AbstractBase::~AbstractBase() {} // Implementation of Pure Virtual Destructor
class Derived : public AbstractBase {};
// No overriding of destructor necessary
int main() { Derived d; }
Here are some of the major differences between Virtual and Pure Virtual Functions
Virtual Functions
Pure Virtual Functions
Virtual Functions
- Virtual functions have a function body.
- Overriding can be done by the virtual functions. (Optional)
- It is define as : virtual int myfunction();
Pure Virtual Functions
- Pure virtual functions have no function body.
- Overriding is must in pure virtual functions. (Must)
- It is define as : virtual int myfunction() = 0;
- A class is called as "abstract class" when it has at least one pure virtual function.
- You can not create instance of "abstract class", rather you have to inherit the "abstract class" and overload all pure virtual function
0 comments:
Post a Comment