int main()
{
use(aPhone);
use(aPager);
}
Do you expect anyone to take that main() function seriously? Where is the declaration of aPhone and aPager? What types are those variables: ints? base class types? derived class types?
The idea is to:
1)create an instance of the derived class
2)create a base class pointer
3)assign the address of the derived class to the base class pointer
4)call functions using the base class pointer and see what happens
If you use the keyword virtual for a function, then you will get dynamic binding, which means the compiler will look at the type pointed to by the base class pointer at runtime, and use that type's version of the function. Without the virtual keyword you get static binding at compile time, which means the compiler uses the base class pointer's version of the function.
Here is an example:
Code:
#include <iostream>
using namespace std;
class Base
{
public:
Base(int n)
{
num1 = n;
}
virtual void print(void)
{
cout<<"Base Class: "<<num1<<endl;
}
void identify(void)
{
cout<<"This is the Base class function."<<endl;
}
private:
int num1;
};
class Derived: public Base
{
public:
Derived(int n, double d):Base(n)
{
num2 = d;
}
void print(void)
{
cout<<"Derived class: "<<num2<<endl;
}
void identify(void)
{
cout<<"This is the Derived class function."<<endl;
}
private:
double num2;
};
int main()
{
Derived d(1, 20.0);
Base* pbase = &d;
pbase->print();//dyanmic binding
pbase->identify();//static binding
return 0;
}