TL ; DR:
C++ has no super keyword. To run the parent's version of an overridden method, call it by its qualified name: Dog::bark();. This lets you extend the parent's behavior instead of replacing it.
class Puppy : public Dog {
public:
Puppy(string name) : Dog(name) {}
void bark() override {
Dog::bark(); // do everything the parent did
cout << "Yip! Said " << name << endl;
}
};
Why it matters
Overriding a method replaces the parent's behavior. Often you want to extend it instead: keep what the parent did and add something more. A typical example is a save method: the parent writes the row to the database, and a subclass runs the parent's save first and then writes a log line.
Your task
The Puppy class already overrides bark(), but the body is empty. Inside Puppy::bark():
- call the parent's version with
Dog::bark();, soWoof! I am <name>still prints; - then
cout << "Yip! Said " << name << endl;.
Notes:
Dog::bark()means "thebarkthat belongs toDog", called on the current object. Writing justbark()insidebarkwould call itself forever.Dog'sbarkisvirtualandPuppy's is markedoverride; both are already written.
The driver (already written, it runs when you press Run):
Puppy buddy("Buddy");
buddy.bark();
Puppy rex("Rex");
rex.bark();
Dog dog("Max");
dog.bark();
buddyis aPuppy: itsbarkprints the parent's line, then its own.rexis anotherPuppy: the names come from the object, nothing is hard-coded.dogis a plainDog: itsbarkis unchanged and prints only the parent's line, with noYip!.
Expected output:
Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
Free plan: 30 tutor messages. Premium is unlimited.
