3i Infotech Papers: Sample Questions 656 - 656 of 1245

Examrace Placement Series prepares you for the toughest placement exams to top companies.

Question number: 656

» Languages » C & C Plus Plus

Essay Question▾

Describe in Detail

Find the output of the following program

  1. class base
  2. {
  3.     public:
  4.     Virtual void baseFun ()
  5.     {
  6.         cout<< “from base” <<endl;
  7.     };
  8. }
  9. class deriPublic base
  10. {
  11.     public:
  12.     Void baseFun ()
  13.     {
  14.         cout<< “from derived” <<endl;
  15.     }
  16. };
  17. void SomeFunc (base * baseObj)
  18. {
  19.     baseObj → baseFun ();
  20. }
  21. int main ()
  22. {
  23.     base baseObject;
  24.     SomeFunc (&baseObject);
  25.     deri deriObject;
  26.     SomeFunc (&deriObject);
  27. }

Explanation

  • In the program

Table showing the program

Table showing the program

  1. class base
  2. {
  3.     public:
  4.     Virtual void baseFun ()
  5.     {
  6.         cout < < “from base” < < endl;
  7.     };
  8. }
  • In base class defines the virtual baseFun () function

  • In a baseFun () cout prints “from base”

  1. class deriPublic base
  2. {
  3.     public:
  4.     Void baseFun ()
  5.     {
  6.         cout < < “from derived” < < endl;
  7.     }
  8. };
  • In deri class define the void baseFun () function

  • In a baseFun () cout prints “from derived”

  1. void SomeFunc (base * baseObj)
  2. {
  3.     baseObj → baseFun ();
  4. }
  • SomeFunc expects a pointer to a base class.

  1. int main ()
  2. {
  3.     base baseObject;
  4.     SomeFunc (&baseObject);
  5.     deri deriObject;
  6.     SomeFunc (&deriObject);
  7. }
  • Define the base () function object baseObject

  • SomeFunc () function pass the baseobject address

  • Define the deri () function object deriObject

  • SomeFunc () function pass the deriobject address

  • Since a pointer to a derived class object is passed.

  • Remember that baseFunc is a virtual function.

  • That means that it supports run-time polymorphism.

  • So the function corresponding to the derived class object is called