用途:
在全局程序域类使用某一类型对象(基类 Base Class), 一般不实例化基类,
而是实例化基类的派生类,
在全局程序内我们只关心这类对象的行为(基类中的虚函数),而不关心
其具体实现(在派生类中override 基类的方法)
最后,释放为派生类分配的存储空间。
Example Code:
class Base
{
public:
Base();
virtual ~Base(); //attention keyword virtual,
//only declare as virtual, when delelte pBase
// can call pDerive->~Derive(), and free the space allocate for object of derive class.
public:
virtual int method1();
virtual int method2();
.
.
.
private:
int var;
.
.
};
class Dervie : public Derive
{
public:
Dervie ();
virtual ~Dervie (); //attention keyword virtual,
//only declare as virtual, when delelte pBase
// can call pDerive->~Derive(), and free the space allocate for object of derive class.
public:
int method1();
int method2();
.
.
.
};
void func(Base **ppBase)
{
*ppBase=new Derive;
}
int main()
{
Base *pBase;
func(&pBase);
delete pBase;
return 0;
}