![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programming Guru
![]() Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 6
![]() |
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. |
|
|
|
|
|
#2 |
|
Programmer
|
That's awesome!
This is...C-something, right? I'm not going to guess which one...it's been far too long since I've known a C-language.
__________________
I had a dream that Triumph the Insult Dog owned Microsoft... How...appropriate. |
|
|
|
|
|
#3 |
|
Programming Guru
![]() |
c++ it has class's in it,.
|
|
|
|
|
|
#4 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
I love virtual functions - they're great when you need to replace a switch() statement with something faster.
|
|
|
|
|
|
#5 | |
|
Programmer
|
Quote:
__________________
I had a dream that Triumph the Insult Dog owned Microsoft... How...appropriate. |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|