How do I call the parent function from a dervied class using C++? For example, assume I have a class called parent, and a class call child which is derived from parent. within each there is a print function. In the defintion 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?
Do something like this:
void child::print(int x)
{
parent::print(x);
}
If your base class is called Base
, and your function is called FooBar()
you can call it directly using Base::FooBar()
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();
}
};
Incidentily, 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
};
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)
}
};
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.