Thread: good for n00bs
View Single Post
Old Apr 30th, 2005, 2:06 AM   #1
bl00dninja
Programming Guru
 
bl00dninja's Avatar
 
Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 6 bl00dninja is on a distinguished road
good for n00bs

here is a simple program demonstrating virtual functions. good to analyze if you're just getting into that sort of thing (like me :-) ).

#include <iostream>
#include <conio.h>
using namespace std;

//  base class
class animal
{
      public:
             //want to show when constuctor/destructor are called
             animal(){cout<<"constructor called..."<<endl;};
             virtual ~animal(){cout<<"\ndestructor called..."<<endl;};
             virtual void speak(){cout<<"\nanimal sound!\n"<<endl;}
             
};

//derived classes follow...

class dog : public animal
{
      public:
             void speak(){cout<<"\nwoof!\n"<<endl;}
};
                     
class chicken : public animal 
{
      public:
             void speak(){cout<<"\ncluck!\n"<<endl;} 
};

class cow : public animal
{
      public:
             void speak(){cout<<"\nmoo!\n"<<endl;}
};

class cat : public animal
{
      public:
             void speak(){cout<<"\nmeow!\n"<<endl;}
};  
//end of classes

           

int main()
{
    //  pointer to base class
    animal * base;
    //  variable for animal type
    int choice;
    //  variable for quitting
    char quit;
    
    do
    {
        cout<<"let's use polymorphism to make animal sounds!"<<endl;
        cout<<"1.\tdog\n2.\tchicken\n3.\tcow"<<endl;
        cout<<"4.\tcat\n5.\tbase animal"<<endl;
        cin>>choice;
    
        switch (choice)
        {
               case 1:
                    base = new dog;
                    break;
                
               case 2:
                    base = new chicken;
                    break;
                
               case 3:
                    base = new cow;
                    break;
                    
               case 4:
                    base = new cat;
                    break;      
                
               default:
                    base = new animal;
                    break;
        }           
    
        //  call appropriate "speak" function
        //  using virtual functions   
        base->speak();
    
        //  quitting condition test
        cout<<"wanna quit?"<<endl;
        cin>>quit;
          
        if (quit == 'y')
        {
                 //  free memory of animal objects
                 delete base;
        }
    
    }while (quit != 'y');
    
    //pause program
    getch();
    
    return 0;
}//  end main
__________________
i put on my robe and wizard hat...

Have you ever heard of Plato, Aristotle, Socrates?...Morons.
bl00dninja is offline   Reply With Quote