-3

So, I got a code like this:

class Fruit
{//some constructor method and instance in here}

class Banana: public Fruit
{//some constructor method and instance in here}

class plant
{
public:
    plant(){
      thisFruit->Banana();//everytime a new plant is created, its thisFruit will point to a new Banana Object
    }
private:
    Fruit *thisFruit;//this plant has a pointer to a fruit
}

however, I got an error in the "this-Fruit->banana();" that state "pointer to incomplete class type is not allowed. is there something wrong with my code? thx

  • 2
    Yeah. Check your favorite tutorial/book on what `->` does. Even though it looks like an arrow, that does not mean that it makes stuff point to other stuff. – us2012 Feb 17 '13 at 23:09
  • I recommend you pick up [an introductory C++ book recommended by the C++ community on Stack Overflow (click on this link)](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). There's a severe misunderstanding of what the `->` operator does here. – In silico Feb 17 '13 at 23:11

3 Answers3

2

If you want thisFruit to point to a Banana object you need to initialize thisFruit with a Banana object

plant::plant()
: thisFruit(new Banana())
{
}

Make sure you follow rule of three, when you have native pointer as member though. Have a read rule of zero as C++11 is around the corner.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
billz
  • 44,644
  • 9
  • 83
  • 100
1

This

thisFruit->Banana();

doesn't make any sense. You probably mean

thisFruit = new Banana();

Make sure to delete thisFruit in your destructor and provide a suitable assignemt operator though. Or make life easy for yourself and use a smart pointer, e.g. boost::scoped_ptr<Fruit> or std::unique_ptr<Fruit>.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

You must use std::unique_ptr or another smart pointer and initialize it with a new Banana:

#include <memory>

class Fruit {
    //some constructor method and instance in here
}

class Banana : public Fruit {
    //some constructor method and instance in here
}

class Plant {
public:
    Plant() : thisFruit{new Banana} {
        
    }

private:
    std::unique_ptr<Fruit> thisFruit; //this plant has a pointer to a fruit
}

See Rule of Zero and The Definitive C++ Book Guide and List.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109