Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2008
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Multiple classes inheriting parent

    Working in C++ here. Here's the simplified problem: I need multiple classes to all inherit from the base class, let's say "Fruit" for now. I keep all of my classes in separate files (.cpp and .h files), where .h has mainly prototypes and .cpp contains function defs. I'm having issues with the #include statements. Apple works fine, but when I incorporate Orange, I get errors concerning class redifinition? I can't figure out where to put the include statements, because putting it in my driver.cpp throws the same errors!

    Driver.cpp:
    Code:
    #include <string>
    #include "Apple.h"
    #include "Orange.h"
    using namespace std;
    
    int main () {
    	return 0;
    }
    Fruit.h:
    Code:
    #include <string>
    using namespace std;
    
    class Fruit {
    	public:
    		Fruit () {};
    	protected:
    		string name;
    		string color;
    };
    Apple.h:
    Code:
    #include "Fruit.h"
    using namespace std;
    
    class Apple : public Fruit {
    	public:
    		Apple () {};
    };
    Orange.h:
    Code:
    #include "Fruit.h"
    using namespace std;
    
    class Orange : public Fruit {
    	public:
    		Orange () {};
    };
    Last edited by TurkeyMaster77; 11-18-2008 at 10:03 AM. Reason: Specified language

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    It is because you are not protecting your includes with preprocessor definitions. Basically when you include orange.h and apple.h they each will bring in a copy of fruit.h which then leads to the code in fruit.h being repeated.

    An example of protecting it would be for your fruit.h:
    Code:
    #include <string>
    using namespace std;
    
    #ifndef FRUIT_H
    #define FRUIT_H
    class Fruit {
    	public:
    		Fruit () {};
    	protected:
    		string name;
    		string color;
    };
    #endif
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •