[Solved] Do I need to initiate parent class or just child class


I suspect that the code you are looking at was written to demonstrate how pointers to base classes can be used with objects of derived classes. No, pointers are not necessary for the functionality of this learning exercise. In fact, that is probably the reason this functionality was chosen. Since you see how to accomplish the same thing without pointers, it should be easier for you to relate pointers to what you already know.

The key learning points I see in this exercise are

  1. The same pointer type (fruit *) can point to objects of different types (apple or pear).
  2. When using the pointer to the base class, you can access base class members.
  3. When using the pointer to the base class, you cannot access derived class members. (Implied by omission; compare what is done with k to what is done with fruit1.)

You will need to move on to the more advanced lessons to learn when pointers are more useful than accessing objects directly (probably after eat() is turned into a virtual function). For now, just learn how the same task can be accomplished by different means.

(Sure, you could get that information here, but that code looks like it’s part of a series. Continuing with that series might be the better way to learn.)

1

solved Do I need to initiate parent class or just child class