Click here to Skip to main content
15,918,193 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In this code if we can access show() of class y with its own object then why are we making show as a virtual function in class x?

C++
#include<iostream.h>
#include<conio.h>

class x
{
      public:
             virtual void show()
             {
                     cout<<"Base show()"<<endl;
             }
};

class y:public x
{
      public:
             void show()
             {
                  cout<<"Class y show()";
             }
};

int main()
{
    x *bp,ob;
    y ob1;
    ob1.show();
    getch();
    return 0;
}
Posted
Updated 6-Aug-11 3:50am
v2

That's the problem with made up classroom examples. The instructor is trying to introduce you to "polymorphism". You really need to read more about that and why it's important in OOP.
 
Share this answer
 
Because all Dog-s bark() but the barking of
a GreatDane is different from the bark of a Beagle.
Hence:

C++
class Dog
{
public:
    virtual void bark() =0;
};

class Beagle: public Dog
{
public:
    virtual void bark() { cout << "bark!"; }
};

class GreatDane: public Dog
{
public:
    virtual void bark() { cout << "BARK!"; }
};
 
Share this answer
 
v3
Thats the reason:
C++
class x
{
public:
  void  DoJob()
  {
    // do anything and final:
    show();
  }

  virtual void show()
  {
    cout<<"Base show()"<<endl;
  }
};
 
class y:public x
{
public:
  void show()
  {
    cout<<"Class y show()";
  }
};
 
int main()
{
  y ob1;
  ob1.DoJob();
  getch();
  return 0;
}

After the job - the show() of class y is called. So you can override functions to implement a different behaviour on a virtual function call.
Regards.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900