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
};
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.
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)
}
};
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
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
}
};
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.
Related
I have a class hierarchy like this:
class Base
{
public:
void start() { init(); }
private:
virtual void init() = 0;
};
class Default : public Base
{
private:
virtual void init() override {/*default implementation*/};
};
class Special : public Default
{
private:
virtual void init() override final {/*specialized implementation*/};
}
Which works alright if I call start() on an object of type Special;
Now I have a case where in the implementation in the Special class I want to call the implementation of the Default class.
Normally that would work with Default::init();, but will fail here due to the Defaults declaration of this is private.
Obviously one solution is to change this from private to protected, but I'd like to ask if there is another way? Rather than allowing any child to call this function directly, I'd like to limit this to calls that are initiated via virtual functions already defined in the Base or Default class.
Is there some option or modifier that would allow member function calls to be only allowed from child classes if they are within (the same) overriding virtual member functions?
C++ doesn't provide means to achieve this directly, so you'd have to work around, e. g. in piece of code below.
Well, if you absolutely want to. I personally would rather just fall back to making the functions protected, document what they are intended for and when to be called, and then just trust the deriving classes to do the stuff right. That in the end keeps the interfaces cleaner and doesn't rely on a rather unusual (and perhaps ugly) pattern (actually passing this twice).
class Base
{
public:
virtual ~Base() { }
void start()
{
InitProxy p(*this);
init(p);
}
protected:
class InitProxy
{
public:
InitProxy(InitProxy const&) = delete;
void init()
{
m_base.Base::init(*this);
}
private:
friend class Base;
Base& m_base;
InitProxy(Base& base)
: m_base(base)
{ }
};
private:
virtual void init(InitProxy& proxy) { }
};
class Derived : public Base
{
void init(InitProxy& proxy) override
{
proxy.init();
}
};
You could let the proxy accept a member function pointer, if you want to apply this constraint to more than one function, so you wouldn't have to re-write the proxy for every function separately. Possibly you'd need to make a template from then, if function parameters differ.
Forward declare Special, and make it a friend of Default:
class Base
{
public:
void start() { init(); }
private:
virtual void init() = 0;
};
class Special; // Forward declaration
class Default : public Base
{
private:
virtual void init() override {/*default implementation*/}
friend class Special; // Friend declaration
};
class Special : public Default
{
private:
virtual void init() override final {
Default::init();
/*Other implementation*/
}
};
I am not able to call a pure virtual function of the base class within a lambda of the inherited class. I simplified the problem to the following easy example...
The usecase is, that the class Test should again be a base class of some other class, that will implement the pure virtual function (anywhere in the program).
class Base
{
public:
virtual void DoSomething(Parameter* p) = 0;
};
class Test : public Base
{
public:
void addFunction()
{
mFunction = [this] (Parameter* p) { Base::DoSomething(p); };
}
private:
std::function<void(Parameter* p)> mFunction;
};
I get following compilation error:
undefined reference to Base::DoSomething(Parameter* p)
My current solution is to call a tempFunction in the base class, and then call the virtual function. But this seems more like a hack... and means unnecessary overhead:
class Base
{
public:
virtual void DoSomething(Parameter* p) = 0;
protected:
void tempDoSomething(Parameter* p) { DoSomething(p); } // call this function instead
};
I am using Android-NDK with clang compiler.
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
};
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.
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)
}
};
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
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
}
};
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.
The content
The question
Example
Why do I need it
Hi.
The question
I am facing a problem. I have a class A that has a base B (is polymorphic). In B class is method Print(), wich is virtual. In A class is also Print(). virtual.
Lets say I am given an A type object (or pointer), stored in B variable
B * object = new A();
And by calling
object->Print();
It calls the method in A class, but I also want it to call method in B class.
Technically
I want to call the method for each child until i reach class that has no child
This can be done as follows:
Example
class A
{
public:
virtual void Print() const override
{
cout << "A" << endl;
}
};
class B : public A
{
public:
virtual void Print() const override
{
cout << "B" << endl;
A::Print(); // i do not want to call it here...
}
};
The problem is that I do want not to be forced to call the
A::Print();
Why
Yes, you might be asking, what is the deal...
I have very long inheritance chain. (lets say that there are like 15 - 20 classes in the inheritance chain).
In a game, each one does some little thing.
Lets say
class GameObject
{
public:
virtual void Update() const
{
//updates position, recounts it towards screen
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
Now this example is very simplified. Problem is, that if i forget to add a call base::Update() Then I am worndering why does it not work. Looking for such a misstake is hard. I mean, if there any way around it?
Thank you very much indeed for any responses.
Have a nice day
If indeed every class must call the base function, one way to ensure the functionality is enforced is to use the template pattern.
class GameObject
{
public:
void Updater()
{
Update(); // this is a virtual call
GameObject::Update(); // now call base
}
virtual void Update() const
{
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
Then always call YourObject::Updater(); instead of YourObject::Update(). The Updater function will call your object's Update function, and then return and call the base class Update.
There was once a proposal to get all the bases of a given type (N2965) which gcc actually implemented in <tr2/type_traits>. So, if portability is not a concern and you happen to be using gcc, you can write a catch-all like so:
struct A {
virtual ~A() = default;
virtual void print() { print_all(*this); }
void print_one() { std::cout << "A\n"; }
protected:
template <class T>
void print_all(T& object) {
object.print_one();
print_all(object, typename std::tr2::bases<T>::type{});
}
template <class T, class... Bases>
void print_all(T& object, std::tr2::__reflection_typelist<Bases...> ) {
using swallow = int[];
(void)swallow{0,
(static_cast<Bases&>(object).print_one(), 0)...
};
}
};
This splits up print(), which prints everything, and print_one() which just prints the one specific type. You just have your print() call print_all() with itself:
struct B : A {
void print() override { print_all(*this); }
void print_one() { std::cout << "B\n"; }
};
struct C : B {
void print() override { print_all(*this); }
void print_one() { std::cout << "C\n"; }
};
Otherwise, you'll have to wait for one of the reflection proposals to get adopted.
class Foo
{
public:
void action();
};
class Bar : public Foo
{
public:
void action();
};
void Foo::action ()
{
cout << "parent\n";
};
void Bar::action ()
{
cout << "child\n";
};
int main()
{
Foo* foo = new Bar ();
foo->action(); // returns "parent" - "child" expected
return 1;
}
I'm sorry for a probably trivial question, but I'm new to C++...
The 'foo' pointer must point to an instance of Foo class, since it can be any of Foo's childs e.g. Bar, Bar1, Bar2, Bar3 etc.
And at the same time 'foo->action()' should run an overridden function of the child.
Tell me please, how do I correct the code to reach my goals...
Thanks!
Unlike other languages, like Java, in C++ base class have to specifically mark the methods it allows overriding of by using keyword virtual
The member function needs to be declared virtual (unlike Java for example, where all methods are implicitly virtual):
class Foo
{
public:
virtual void action();
};
Use keyword virtual for parent-class function. And also, your parent class should have virtual destructor.
class Foo
{
public:
virtual void action();
};
class Bar : public Foo
{
public:
void action();
};
void Foo::action ()
{
cout << "parent\n";
};
void Bar::action ()
{
cout << "child\n";
};
int main()
{
Foo* foo = new Bar ();
foo->action(); // returns "parent" - "child" expected
return 1;
}