Start learning free

LESSON 400 OF 409 · OBJECT-ORIENTED PROGRAMMING

Calling the Parent with Dog::bark() in C++ in C++

Practice

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():

  1. call the parent's version with Dog::bark();, so Woof! I am <name> still prints;
  2. then cout << "Yip! Said " << name << endl;.

Notes:

  • Dog::bark() means "the bark that belongs to Dog", called on the current object. Writing just bark() inside bark would call itself forever.
  • Dog's bark is virtual and Puppy's is marked override; 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();
  • buddy is a Puppy: its bark prints the parent's line, then its own.
  • rex is another Puppy: the names come from the object, nothing is hard-coded.
  • dog is a plain Dog: its bark is unchanged and prints only the parent's line, with no Yip!.

Expected output:

Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
STEP 1 OF 2
    Ctrl + Enter to check

    Base Keyword in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free