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?
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
};
Why would you like to inherit from the same class twice ?
@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.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.
@Mathai And that is why you aren't supposed to use
using namespace std
.+1 for stating
You should note that unlike Java and C#, C++ does not have a keyword for "the base class"
.