c++ Assuming the following inheritance: class Plant { public: Plant ( ); ~Plant
ID: 3915487 • Letter: C
Question
c++
Assuming the following inheritance:
class Plant {
public:
Plant ( );
~Plant ( );
void grow ( ); // only defined in base class Plant, not re-defined in derived class Cactus
} ;
class Cactus : public Plant {
public:
Cactus ( );
~Cactus ( ) ;
void produce_spines ( ); // For your information: spines are similar to thorns
// This function is Cactus-specific as not every plan produces spines
} ;
1. Declare a pointer to a Plant object and properly initialize it.
2. Dynamically instantiate (create) a Cactus object using default constructor and assign the address of the object to the Plant pointer declared in step 1.
3. Invoke the grow member function for the newly created Cactus object.
4. Invoke produce_spines member function for the Cactus object. You may declare new variable if needed.
5. You're done with the Cactus object let's free its memory. Make sure when Cactus object is destroyed both Cactus' constructor and Plant's constructor are called.
6. Assuming now the Plant::grow member function must be redefined in Cactus class. The requirement is that if the grow function is called via a Plant pointer then the Cactus::grow version will be called instead. What else do you need to modify in the Plant class after the feature above is implemented? Rewrite the class declarations for both Plant and Cactus classes to show your modification.
Explanation / Answer
// 1. Declare a pointer to a Plant object and properly initialize it. Plant *plant = NULL; // 2. Dynamically instantiate (create) a Cactus object using default constructor and assign the address of the object to the Plant pointer declared in step 1. plant = new Cactus(); // 3. Invoke the grow member function for the newly created Cactus object. plant->grow(); // 4. Invoke produce_spines member function for the Cactus object. You may declare new variable if needed. Cactus *c = (Cactus *)(plant); c->produce_spines(); // 5. You're done with the Cactus object let's free its memory. Make sure when Cactus object is destroyed both Cactus' constructor and Plant's constructor are called. delete plant;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.