Note that there are some explanatory texts on larger screens.

plurals
  1. POpolymorphism concept
    primarykey
    data
    text
    <p>I'm getting a "Segmentation Fault" while running this program. Please differentiate between the below two programs</p> <pre><code>class xxx{ public: virtual void f(){cout&lt;&lt;"f in xxx"&lt;&lt;endl;} //virtual function virtual void g(){cout&lt;&lt;"g in xxx"&lt;&lt;endl;} //virtual function }; class yyy{ //yyy has no relation with xxx at this context public: virtual void f(){cout&lt;&lt;"f in yyy"&lt;&lt;endl;} //virtual function but no relation with xxx class void g(){cout&lt;&lt;"g in yyy"&lt;&lt;endl;} }; int main(int argc, char *argv[]) { xxx x1,*x; yyy y1; x=&amp;x1; x-&gt;f(); x-&gt;g(); x=(xxx*) &amp;y1; //one class pointer containing another class object address x-&gt;f(); x-&gt;g(); } </code></pre> <p><strong>- Output</strong></p> <pre><code>f in xxx g in xxx f in yyy Segmentation fault </code></pre> <p>But according to polymorphism concept with the same problem </p> <pre><code>class xxx{ public: virtual void f(){cout&lt;&lt;"f in xxx"&lt;&lt;endl;} //virtual function virtual void g(){cout&lt;&lt;"g in xxx"&lt;&lt;endl;} //virtual function }; class yyy:public xxx{ //yyy is derived from xxx public: virtual void f(){cout&lt;&lt;"f in yyy"&lt;&lt;endl;} void g(){cout&lt;&lt;"g in yyy"&lt;&lt;endl;} }; int main(int argc, char *argv[]) { xxx x1,*x; yyy y1; x=&amp;x1; x-&gt;f(); x-&gt;g(); x=(xxx*) &amp;y1; //parent class pointer having derived class address x-&gt;f(); x-&gt;g(); } </code></pre> <p><strong>- Output</strong></p> <pre><code>f in xxx g in xxx f in yyy g in yyy </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload