inheritance - C++: Field has incomplete type -
i trying implement strategy design pattern exercise. classes pretty simple:
1) fly.cpp
class fly { public: fly(); bool fly(); }; class canfly : public fly { public: bool fly() { return true; } }; class cantfly : public fly { public: bool fly() { return false; } };
2) animal.cpp
class fly; class animal { fly myfly; public: animal(fly f); void setfly(fly f); fly getfly(); }; animal::animal(fly f) { myfly = f; } void animal::setfly(fly f) { myfly = f; } fly animal::getfly() { return myfly; }
3) dog.cpp
#include <iostream> using namespace std; class animal; class dog : public animal { public: dog(fly f); }; dog::dog(fly f) { setfly(f); cout << "dog : " << getfly().fly() << endl; }
4) bird.cpp
#include <iostream> using namespace std; class animal; class bird : public animal { public: bird(fly f); }; bird::bird(fly f) { setfly(f); cout << "bird : " << getfly().fly() << endl; }
5) animaltest.cpp
#include <iostream> using namespace std; class dog; class bird; class canfly; class cantfly; int main() { fly f1 = new canfly(); fly f2 = new cantfly(); bird b(f1); dog d(f2); return 0; }
the error upon building code :
animal.cpp:5:6: error: field 'myfly' has incomplete type 'fly' fly myfly; ^
can me why?
thanks
incomplete type error means compiler doesn't see definition of class, declaration. if create object or if pass object value need provide definition of class compiler. create objects , pass them around values hence need include definition of relevant classes pass cpp files.
but not want do. intention employ polymorphism need pass objects reference or pointer instead.
your animal class should be:
class animal { fly &myfly; public: animal(fly &f); void setfly(fly &f); fly const &getfly(); };
that way can pass of fly, canfly, or cantfly objects animal object.
you need reorganise code. need separate class definitions header files. example:
//animal.h class fly; <=== declaration. ok here. class animal { fly &myfly; public: animal(fly &f); void setfly(fly &f); fly const &getfly(); };
then need include headers cpp. example:
#include "animal.h" class dog : public animal <=== compiler needs definition of animal here { public: dog(fly f); };
note difference between following definitions:
fly animal::getfly() { return myfly; }
returns copy of object stored in myfly.
fly const &animal::getfly() { return myfly; }
returns constant reference object myfly
also, perhaps, not need fly, canfly, cantfly
classes @ all. classes bird, dog
"know" if can or cannot fly. sure, doing exercise still fly, canfly, etc seem redundant , artificial here.
Comments
Post a Comment