OK assuming you read the Visitor article, here we go.
The idea is to use an animal pointer that points to one of your animals ( a cow or a bird) and use it to call a method on the derived class. That is, it the pointer points to a cow then the idea is to call a cow method using an animal pointer. That way you can use an animal pointer to change the numberoflegs on a cow.
This is the main():
- int main()
-
{
-
animal* ptr = new cow;
-
Visitor v;
-
ptr->Visit(&v);
-
ptr->displaydata();
-
-
}
You create a cow and use it as an animal pointer.
Next, you visit the object using a Visitor pointer. That will set the number of legs.
Next, you display the data for the cow.
This is the code to make the main() work:
- class cow;
-
class bird;
-
class Visitor
-
{
-
public:
-
void ItsACow(cow* obj);
-
void ItsABird(bird* obj);
-
-
};
-
-
-
class animal {
-
protected:char sound[10];
-
int fly;
-
public:virtual void displaydata() = 0;
-
void Visit(Visitor* obj);
-
private: virtual void DoVisit(Visitor* obj);
-
};
-
void animal::Visit(Visitor* obj)
-
{
-
DoVisit(obj);
-
}
-
void animal::DoVisit(Visitor* obj)
-
{
-
return;
-
}
-
-
-
-
-
class cow : public animal {
-
private:int numberoflegs;
-
public : void displaydata();
-
public: void DoVisit(Visitor* obj);
-
public: void SetLegs(int val);
-
-
};
-
-
class bird : public animal {
-
public:void displaydata();
-
};
-
-
-
-
void cow::SetLegs(int val)\
-
{
-
this->numberoflegs = val;
-
}
-
void cow::displaydata()
-
{
-
cout << "A cow has " << numberoflegs << " legs."<< endl;
-
}
-
void bird::displaydata()
-
{
-
cout << "Tweet. Tweet." << endl;
-
}
-
-
void cow::DoVisit(Visitor* obj)
-
{
-
obj->ItsACow(this);
-
}
-
-
void Visitor::ItsACow(cow* obj)
-
{
-
//Set the cow's number of legs here
-
obj->SetLegs(4);
-
}
-
-
int main()
-
{
-
animal* ptr = new cow;
-
Visitor v;
-
ptr->Visit(&v);
-
ptr->displaydata();
-
-
}
I suggest you follow this code using the insight article and then step through it with your debugger to see how the design pattern works.
Then post again if you still have questions.
I only implemented the cow.