801

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?

3
  • 3
    I wouldn't use the MSVC __super since it's platform specific. Although your code may not run on any other platform, I'd use the other suggestions since they do it as the language intended.
    – Teaser
    Commented Oct 13, 2010 at 23:39
  • Possible duplicate of Can I call a base class's virtual function if I'm overriding it?
    – Archmede
    Commented Aug 9, 2017 at 1:36
  • 1
    The antipattern where derived classes are always required to call parent class functions is Call super
    – Rufus
    Commented Mar 5, 2019 at 3:43

9 Answers 9

1005

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
};
13
  • 48
    Why would you like to inherit from the same class twice ? Commented Oct 5, 2013 at 18:39
  • 89
    @bluesm: in classic OOP it makes no much sense, but in generic programming template<class A, class B> class C: public A, public B {}; can come to two types being the same for reasons depending on how your code is used (that makes A and B to be the same), may be two or three abstraction layer way from someone not aware of what you did. Commented Nov 18, 2013 at 18:37
  • 10
    I think it's useful to add, that this will call parent class method even if it is not implemented directly in the parent class, but is implemented in one of the parent classes in the inheritance chain. Commented Dec 26, 2014 at 10:30
  • 93
    @Mathai And that is why you aren't supposed to use using namespace std.
    – JAB
    Commented Oct 8, 2015 at 21:06
  • 26
    +1 for stating You should note that unlike Java and C#, C++ does not have a keyword for "the base class". Commented Sep 16, 2016 at 8:15
279

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

5
  • Of course, this would only be useful if the base call were interspersed with other logic, otherwise there'd be no point in overriding the function, so maybe it's a little too to-the-point ;) Commented Apr 11, 2016 at 13:20
  • 1
    @underscore_d actually, its useful even if the base call was not interspersed with other logic. Let's say the parent class pretty much does everything you want, but exposes a method foo() you don't want users of child to use - either because foo() is meaningless in child or external callers to child will screw up what child is doing. So child may use parent::foo() in certain situations but provide an implementation of foo so that they hide parent's foo() from being called.
    – iheanyi
    Commented Apr 22, 2016 at 18:56
  • @iheanyi Sounds interesting, but sorry, I'm not grasping it yet. Is foo() here analogous to print() or a separate function? And do you mean by using private inheritance to hide details inherited from the base, and providing public shadowing functions for things you do want to expose? Commented Apr 22, 2016 at 19:02
  • @underscore_d Yes, foo() was analogous to print(). Let me go back to using print() as I think it would make more sense in this context. Let's say someone created a class that carried out some set of operations on a particular datatype, exposed some accessors, and had a print(obj&) method. I need a new class that works on array-of-obj but everything else is the same. Composition results in a lot of duplicated code. Inheritance minimizes that, in print(array-of-obj&) loop calling print(obj&), but don't want clients to call print(obj&) because doesn't make sense for them to do so
    – iheanyi
    Commented Apr 25, 2016 at 15:34
  • @underscore_d This is predicated on the assumption that I can't refactor out the common parts of the original parent class or that doing so is incredibly costly. Private inheritance could work, but then you lose the public accessors which you were relying upon - and would thus, need to duplicate code.
    – iheanyi
    Commented Apr 25, 2016 at 15:37
42

If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}
33

In MSVC there is a Microsoft specific keyword for that: __super


MSDN: Allows you to explicitly state that you are calling a base-class implementation for a function that you are overriding.

// deriv_super.cpp
// compile with: /c
struct B1 {
   void mf(int) {}
};

struct B2 {
   void mf(short) {}

   void mf(char) {}
};

struct D : B1, B2 {
   void mf(short) {
      __super::mf(1);   // Calls B1::mf(int)
      __super::mf('s');   // Calls B2::mf(char)
   }
};

10
  • 5
    Eh, I'd prefer typdefing the parent as something like super. Commented Nov 1, 2011 at 19:06
  • 27
    I won't try to justify usage of __super; I mentioned it here as an alternative suggestion. Developers should know their compiler and understand pros and cons of its capabilities.
    – Andrey
    Commented Jan 30, 2012 at 1:56
  • 14
    I'd rather discourage anyone from using it, as it severely hinders portability of the code.
    – Erbureth
    Commented Mar 13, 2014 at 13:42
  • 30
    I don't agree with Andrey: Developers should know the standard and should not need to bother with compiler features, if we consider writing software which is primarily compiler independent which I think is a good idea anyways because sooner or later in large projects multiple compilers are anyways used.
    – Gabriel
    Commented Dec 11, 2014 at 17:39
  • 12
    "Developers should know their compiler" this reasoning, and the inclusion of non standard features, is what led to IE6...
    – Déjà vu
    Commented Aug 4, 2016 at 10:50
12

Call the parent method with the parent scope resolution operator.

Parent::method()

class Primate {
public:
    void whatAmI(){
        cout << "I am of Primate order";
    }
};

class Human : public Primate{
public:
    void whatAmI(){
        cout << "I am of Human species";
    }
    void whatIsMyOrder(){
        Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
    }
};
10

If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class. Call to the base class non-virtual and virtual member function from derived member function can be made. Please refer the program.

#include<iostream>
using namespace std;

class Parent
{
  protected:
    virtual void fun(int i)
    {
      cout<<"Parent::fun functionality write here"<<endl;
    }
    void fun1(int i)
    {
      cout<<"Parent::fun1 functionality write here"<<endl;
    }
    void fun2()
    {

      cout<<"Parent::fun3 functionality write here"<<endl;
    }

};

class Child:public Parent
{
  public:
    virtual void fun(int i)
    {
      cout<<"Child::fun partial functionality write here"<<endl;
      Parent::fun(++i);
      Parent::fun2();
    }
    void fun1(int i)
    {
      cout<<"Child::fun1 partial functionality write here"<<endl;
      Parent::fun1(++i);
    }

};
int main()
{
   Child d1;
   d1.fun(1);
   d1.fun1(2);
   return 0;
}

Output:

$ g++ base_function_call_from_derived.cpp
$ ./a.out 
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here
1
  • 4
    Thank you for bringing some examples with virtual!
    – M.Ionut
    Commented Apr 5, 2020 at 21:06
0

In C++, when you have a base class (parent) and a derived class (child), and both classes have a function with the same name, you can call the base class's function from the derived class using the scope resolution operator ::.

Let's say you have a parent class with a print function:

    class Parent {
public:
    void print() {
        // Parent's print functionality
    }
};

And you have a derived class that inherits from the parent:

    class Child : public Parent {
public:
    void print() {
        // Child's print functionality

        // To call the parent's print function:
        Parent::print();
    }
};

In the Child class, within the definition of its print function, you can use Parent::print(); to explicitly call the print function of the parent class. This way, you have control over whether to include the parent's functionality in addition to the child's or to override it completely.

1
  • 1
    There are already a number of other answers that same much the same as yours. Please add some explanation as to what your answers offers that other do not. Commented Dec 24, 2023 at 8:42
0

You can convert this to a pointer of your base class and then call the function from that pointer:

((Base*)this)->foo();

Here is a complete example:

#include <iostream>

class Base
{
public:
    void print()
    {
        std::cout << "Base\n";
    }
};

class Derived : public Base
{
public:
    void print()
    {
        std::cout << "Derived\n";
        ((Base*)this)->print();
    }
};

int main() {
    Derived derived;
    derived.print();
}
-20
struct a{
 int x;

 struct son{
  a* _parent;
  void test(){
   _parent->x=1; //success
  }
 }_son;

 }_a;

int main(){
 _a._son._parent=&_a;
 _a._son.test();
}

Reference example.

2
  • 4
    Could you please edit in an explanation of why/how this code answers the question? Code-only answers are discouraged, because they are not as easy to learn from as code with an explanation. Without an explanation it takes considerably more time and effort to understand what was being done, the changes made to the code, or if the code is useful. The explanation is important both for people attempting to learn from the answer and those evaluating the answer to see if it is valid, or worth up voting.
    – Makyen
    Commented Feb 23, 2015 at 5:30
  • 4
    This answer is about nested classes while the question was about derived classes (even though the words 'parent' and 'child' are a bit missleading) and therefore doesn't answer the question at all. Commented Aug 5, 2015 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.