Is multiple function overloading not permitted with virtual functions?
My program compiles fine, but gets core dumped when an overloaded function is called. Below, is the output of the program:
FoodID supplied=1
FoodBase constructor called
In K constructor
In Omlette constructor
Omlette handler constructor called
In prepare() Omlette Handler
Mix called
K Prepare called
K Egg called
DonePreparing called
In egg() Omlette Handler
Segmentation fault (core dumped)
I'm trying to overload the pure virtual function named "egg". The egg function needs to be of two types: One that tak开发者_开发问答es no variables and the other that takes an integer. The one that takes the integer crashes. Help?
#include<iostream>
#include<cstdlib>
using namespace std;
class K
{
public:
K() {cout<<"In K constructor"<<endl;}
protected:
void kPrepare() {cout<<"K Prepare called"<<endl;}
void kEgg() {cout<<"K Egg called"<<endl;}
};
class Omlette : public K
{
public:
Omlette() {cout<<"In Omlette constructor"<<endl;}
protected:
void doPreparation()
{
mix();
kPrepare();
kEgg();
donePreparing();
}
void mix() {cout<<"Mix called"<<endl;}
void donePreparing() {cout<<"DonePreparing called"<<endl;}
};
class FoodBase
{
public:
virtual void prepare()=0;
virtual void egg()=0;
virtual void egg(int)=0;
FoodBase() {cout<<"FoodBase constructor called"<<endl;}
};
class OmletteHandler : public FoodBase, Omlette
{
public:
OmletteHandler() {cout<<"Omlette handler constructor called"<<endl;}
void prepare()
{
cout<<"In prepare() Omlette Handler"<<endl;
doPreparation();//from Omlette class
}
void egg() {cout<<"In egg() Omlette Handler"<<endl;}
void egg(int i) {cout<<"In egg("<<i<<") Omlette Handler"<<endl;}
};
class Food
{
public:
FoodBase *base;
Food(int foodID)//getting foodID from commandline just for testing purpose
{
OmletteHandler immediate;//changed from 'imm' to 'immediate'
base=&immediate;
}//Food
void prepare() {base->prepare();}
void egg() {base->egg();}
void egg(int i) {base->egg(i);}
};
int main(int argc, char *argv[])
{
int foodID=1;
if (argc>1) {foodID = atoi(argv[1]);}
cout<<"FoodID supplied="<<foodID<<endl;
Food f(foodID);
f.prepare();
f.egg();
f.egg(10);
}//main
In the Food constructor you create an OmeletteHandler on the stack, this gets destroyed once the function exits.
Food(int foodID)//getting foodID from commandline just for testing purpose
{
OmletteHandler imm;
base=&imm;
}//
You could do base = new OmeletteHandler()
instead, (don't forget to delete the pointer later or you'll have memory leak).
精彩评论