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
};
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. –
Desmarais virtual
methods. –
Counterword using namespace std
. –
Policewoman You should note that unlike Java and C#, C++ does not have a keyword for "the base class"
. –
Groggy typedef left super;
in your class if you want, then you can refer to super::foo();
. And since you cannot derive from the same class twice directly, you have to do it indirectly struct left1 : left{}; struct left2 : left{}; class bottom : public left1, public left2 { ... };
but you are probably better off using composition rather than inheritance. –
Bulley this->foo(3)
is equivalent to foo(3)
. It will go to the derived method. I also think you may be confusing "overload" and "override", see scaler.com/topics/…. –
Counterword using Super = <BaseClass>
. For example: github.com/microsoft/react-native-windows/blob/…. –
Vibration 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.
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? –
Gillispie 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 –
Congenital 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();
}
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)
}
};
typdef
ing the parent as something like super
. –
Euchre __super
; I mentioned it here as an alternative suggestion. Developers should know their compiler and understand pros and cons of its capabilities. –
Hypertension __super
. It's nice and simple, and for the 99.9% of code which is SANE and doesn't use multiple inheritance, there's no problem with it. Explicitly specifying the base class has led to multiple hard to diagnose horrible bugs in our codebase throughout the years, where people end up accidentally going straight from Level3->Level1 and skipping the Level2 class in the middle; __super prevents this. Also portable code, that's a good point, however not all code cares about being portable –
Nutation __super
doesn't add functionality, because you can name that class explicitly (or get a habit of doing typedef Parent super
right after class declaration if you want to write super
): it's main purpose is to dispatch the function call to one of the two super classes when a method could be in one or another (i.e., mixin scenario). Sacrificing standard compliance may be justified if you explicitly need that functionality, not for lazyness. –
Yiddish 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
}
};
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
virtual
! –
Long 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.
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();
}
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.
© 2022 - 2024 — McMap. All rights reserved.