このプログラムの実行中に「セグメンテーション違反」が発生します。以下の2つのプログラムを区別してください
class xxx{
public: virtual void f(){cout<<"f in xxx"<<endl;} //virtual function
virtual void g(){cout<<"g in xxx"<<endl;} //virtual function
};
class yyy{ //yyy has no relation with xxx at this context
public: virtual void f(){cout<<"f in yyy"<<endl;} //virtual function but no relation with xxx class
void g(){cout<<"g in yyy"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1,*x;
yyy y1;
x=&x1;
x->f();
x->g();
x=(xxx*) &y1; //one class pointer containing another class object address
x->f();
x->g();
}
-出力
f in xxx
g in xxx
f in yyy
Segmentation fault
しかし、同じ問題を持つポリモーフィズムの概念によると
class xxx{
public: virtual void f(){cout<<"f in xxx"<<endl;} //virtual function
virtual void g(){cout<<"g in xxx"<<endl;} //virtual function
};
class yyy:public xxx{ //yyy is derived from xxx
public: virtual void f(){cout<<"f in yyy"<<endl;}
void g(){cout<<"g in yyy"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1,*x;
yyy y1;
x=&x1;
x->f();
x->g();
x=(xxx*) &y1; //parent class pointer having derived class address
x->f();
x->g();
}
-出力
f in xxx
g in xxx
f in yyy
g in yyy