Asked  7 Months ago    Answers:  5   Viewed   35 times

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?

 Answers

63

I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.

class left {
public:
    void foo();
};

class right {
public:
    void foo();
};

class bottom : public left, public right {
public:
    void foo()
    {
        //base::foo();// ambiguous
        left::foo();
        right::foo();

        // and when foo() is not called for 'this':
        bottom b;
        b.left::foo();  // calls b.foo() from 'left'
        b.right::foo();  // call b.foo() from 'right'
    }
};

Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

class bottom : public left, public left { // Illegal
};
Tuesday, June 1, 2021
 
Silfverstrom
answered 7 Months ago
41

Using the Prototype library (www.prototypejs.org):

Javascript:

<script type="text/javascript">
  function toggle()
  {
      var ele = document.getElementById("addCatTextBox");
      var text = document.getElementById("addCatButtonText");
      if(ele.style.display == "block") {
              ele.style.display = "block";
          text.innerHTML = "Save category";

          var options={
            method: 'get',
            parameters: 'inCatName='+ele.value,
            onSuccess: function(xhr) {
                // TODO: Whatever needs to happen on success
                alert('it worked');
            },
            onFailure: function(xhr) {
                // TODO: Whatever needs to happen on failure
                alert('it failed');
            }
          };

          new Ajax.Request('addCategory.php', options);

      }
      else {
          ele.style.display = "none";
          text.innerHTML = "Add new category";
      }
  } 
</script>

addCategory.php:

<?php

$inCatName=isset($_REQUEST["inCatName"]) ? $_REQUEST["inCatName"] : null;

Category::addCategory($inCatName);

?>

The idea is that the Javascript sends a GET (or it could be POST) request to the addCategory.php page behind the scenes, passing it whatever info it needs to create the category.

Hopefully this is enough to get you going. There's a lot missing from my code - you'll need to validate the variables addCategory.php receives and perform any other pertinent security checks before letting it anywhere near the database. addCategory.php will also require any include files, etc so that it knows about your Category class. Finally, addCategory.php should really return some form of variable back to the Javascript code that called it so that it knows what the outcome was.

Wednesday, March 31, 2021
 
SJain
answered 9 Months ago
27

The need for an inheritance chain is questionable, in general.

However the specific scenario of combining an abstract base class with an interface.. I see it this way:

If you have an abstract base class like this, you should also have a corresponding interface. If you have an interface, then use the abstract base class only where the inheritance chain is sensible.

That said, if I'm writing a library and this is part of my API/Framework, I will generally include a "default implementation" that can be used as a base class. It will implement the interface methods in a naive, general way, where possible, and leave the rest for inheritors to implement/override as needed.

This is just a convenience feature of the library though, to assist people who want to implement the interface by providing a functional example that may cover most of what they need to implement already.

In short, the interface is more valuable than the base class, but a base class might save a lot of time and reduce buggy interface implementations.

Wednesday, September 15, 2021
 
Eric
answered 3 Months ago
64

The methods defined in a superclass are accesible to any subclass. But "sister" classes cannot access the (private) methods of one another.

So if your classes Cat and Dog inherit from Animal, then both Cat and Dog objects can call methods from Animal, but they cannot (must not) access the methods of each other.

Tuesday, October 26, 2021
 
Averroes
answered 1 Month ago
63

A contained object has no special access to the class that contains it, and in general does not know that it is contained. You need to pass a reference or a pointer to the containing class somehow - for example:

class Child{
public:
  void doOtherThing( Parent & p );
};

void Child::doOtherThing( Parent & p ){
   p.doSomething();
}
Wednesday, November 10, 2021
 
KMC
answered 4 Weeks ago
KMC
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share