call overwritten child function within parent function - c++

is it possible in c++ to call a child function from a parent function.
Let's take an example: The parent class defines in a function (parse) the general workflow. The workflow then calls different methods which represent part of the flow (parseElementA). These functions can be overwritten by the child class, if not the standart function, which is part of the parent shall be used.
My issue is: I create a child object and execute the workflow function (parse). When the overwritten function (parseElementA) is called within the workflow function it calls the function from the parent and not from the child.
What could i do so it calls the overwritten function in child.
class Parent {
public:
void parse() { parseElementA(); }
virtual void parseElementA() { printf("parent\n"); }
};
class Child : public Parent {
public:
void parseElementA() { printf("child\n"); }
};
Child child;
child.parse();
the output is parent. What can I do that it returns child.
Thank you very much for any advice.

After fixing compiler errors from your code, it works fine.

#include <cstdio>
class Parent {
public:
void parse() { parseElementA(); }
virtual void parseElementA() { printf("parent\n"); }
};
class Child : public Parent {
public:
void parseElementA() { printf("child\n"); }
};
int main() {
Child child;
child.parse();
return 0;
}

Related

Accessing Nested Class Member Function in CPP

In case of nested class, how do I access the "Inner" or "Child" class's member function?.
For example, the code, where I created "obj1". Now how do I access the "childPrint()" with"obj1"?
example_code:
#include<iostream>
using namespace std;
/////////////////////////////////////////////////
class Parent
{
public:
void print()
{
cout<<"this is from Parent"<<endl;
}
class Child
{
public:
void childPrint()
{
cout<<"this is from Child"<<endl;
}
};
};
int main()
{
Parent obj1;
obj1.print();
Parent::Child obj2;
obj2.childPrint();
obj1.Child::childPrint();///ERROR
return 0;
}
Now how do I access the "childPrint()" with"obj1"?
You can't.
obj1 is of type Parent, which doesn't contain any method called childPrint. An instance of Parent doesn't automatically contain an instance of Child (I think Java does something like this), they are still seperate classes. You can only call this method on an instance of Child.
obj1.Child::childPrint();
In this particular line, you need to understand that childPrint() is an instance member function of class Child. So, only an instance of class Child can call childPrint() function.
If childPrint() function is a static member function(class function) of class Child then it is possible to call it without creating any instance and no error will be shown in Parent::Child::childPrint();.
If you have a static method, then you can call it with:
/////////////////////////////////////////////////
class Parent
{
public:
...
class Child
{
public:
static void childPrint() { cout<<"this is from Child"<<endl; };
}
}
...
Parent::Child::childPrint();
These are separate classes without any automatic instanciation of child classes and vice versa.

Access child member methods from function taking parent class

A test function needs to take in any object of a class that is derived from Parent and access the Child implementation of Function(). To me, this would seem like something easy to do. I tried to do the following. it feels intuitively right, but it does not work. It still calls the Parent implementation of Function()
Class Parent
{
Public:
Parent();
~Parent();
virtual void Function() = 0;
};
Class Child : public Parent
{
Public:
Child();
~Child();
void Function(){
// Do something
};
};
void Test(Parent Object)
{
Object.Function();
};
int main()
{
Child Object;
Test(Child);
return 0;
}
How would one implement such a thing?
Am I missing something small? or is this solution far off what I am trying to achieve?
Thanks in advance.
To use virtual functions in C++ you must use a reference or a pointer. Try this
void Test(Parent& Object) // reference to Parent
{
Object.Function();
};
You should research object slicing to understand what goes wrong with your version, and why you must use a reference or a pointer.

How do I call a method in an owning object in c++?

What is the syntax for calling a method in an owning object from an owned object in c++?
Parent class:
class Parent
{
private:
Child child;
public:
Parent()
{
addChild(child);
}
void MethodToBeCalled(int someArgument)
{
}
};
Child class:
class Child
{
private:
void myVoid()
{
//Call parent method somehow
}
public:
Child()
{
}
};
I tried to make my question as simple and generic as possible (to be of benefit to as many as possible). Let me know if I can make it even clearer.
Thank you!
Here's a example. I had to modify your code a bit to get it compile:
class Component {};
class Parent;
class Child : public Component
{
private:
inline void myVoid();
Parent &parent_ref;
public:
Child(Parent &pr) : parent_ref{pr} {}
};
class Parent : public Component {
private:
Child child;
public:
Parent() : child{*this}
{
// addChildComponent(child);
}
void MethodToBeCalled(int someArgument)
{
}
};
inline void Child::myVoid()
{
parent_ref.MethodToBeCalled(1);
}
If you are sure that your Child object is a member subobject of Parent class (as in your example), you can use the container_of trick (see Understanding container_of macro in the Linux kernel)
class Child
{
private:
void myVoid();
};
class Parent
{
public:
Child child;
void MethodToBeCalled(int someArgument)
{
}
};
void Child::myVoid()
{
container_of(this, Parent, child)->MethodToBeCalled(42);
}
Obviously, tricks like this immediately restrict the usability of your Child class to always being a member of Parent class (at least when you intend to call myVoid() method on it).
A much better idea would be to just pass a reference to parent object to child object.
In your case, you can't, because Child and Parent have nothing in common except that they both inherit Component. Child has to have a Parent object in order to call MethodToBeCalled().

Is it possible to cast from super class object to subclass when the objects are not dynamically allocated (not pointers)?

I have a global function within a namespace and this function is a helper function that will create objects and return them. However the return type is of the parent class, but the actual object returned is a subclass of the parent. It is then up to the user to cast it returned "parent" object to the appropriate subclass. I thought this is what polymorphism was about but I am not able to cast the returned object to a subclass. For example:
class Parent {...};
class ChildOne : public Parent {...};
class ChildTwo : public Parent {...};
Parent my_function(int x) {
if(x) {
return ChildOne();
}
else {
return ChildTwo();
}
};
int main() {
// The statement below is giving me an error (no matching function call...)
ChildOne my_child = (ChildOne)my_function(1);
}
No, you cannot cast the object returned by my_function to a subclass of Parent.
Since:
Parent my_function(int x) {
returns the object by value, it always returns an object of class Parent, and never a subclass. This is due to slicing.
For a discussion, see What is object slicing?
It is not possible as it is written in NPE's answer,
Since you asked in comment what you could do instead, this is how you can achieve (more or less) what you want in C++11.
#include <iostream>
#include <memory>
using namespace std;
class Parent {
public:
virtual ~Parent() { }
};
class ChildOne : public Parent {
public:
void say_hello() { cout << "Hello from ChildOne!" << endl; }
};
class ChildTwo : public Parent { };
unique_ptr<Parent> my_function(int x) {
if(x) {
return unique_ptr<Parent>{ new ChildOne() };
}
else {
return unique_ptr<Parent>{ new ChildTwo() };
}
}
int main() {
auto parent = my_function(1);
if (ChildOne* my_child = dynamic_cast<ChildOne*>(parent.get())) {
my_child->say_hello();
}
}
However, I would revise my code in such a way that the downcast (cast from parent to child) is not need. There are certain situations where it is needed or unavoidable but most of the time it is a sign of design flaw.

Call pure virtual function from parent class

I'm very new to c++, but I think I understand what is going on. The parent class is trying to call the pure virtual member function in the parent class. I thought that by overriding the virtual function in the child class, it would be called instead.
What am I doing wrong?
Provided for me in parent.h
class Parent
{
public:
virtual void run() = 0;
protected:
/** The function to starter routine and it will call run() defined by the
* appropriate child class.
* #param arg Arguments for the starter function
*/
static void * init (void * arg);
};
I'm trying to do this in parent.cpp
void * Parent::init(void * arg)
{
run();
}
In my child.h I have this:
class Child : public Parent
{public:
//...
virtual void run();
//...
};
And in child.cpp I have:
void Child::run()
{
sleep(10);
}
The function init in parent.cpp is where this fails to compile. How do I call a derived function from the parent class? All my googleing has only turned up notes about not calling virtual functions in the child's constructor.
Any help at all would be appreciated.
run() is an instance member. Parent::init is a static (class-level) member. So in your init() implementation, there is no instance (of Parent or Child) available on which to call run().
You're trying to call an instance method from a static method. You'll need to change init() to be an instance method (by removing the static keyword) or else you'll need to call the run() method using an object, e.g. obj->run() or obj.run().
Do you know the actual type of arg: is it in fact a Parent instance? If so, then ...
void Parent::init(void* arg)
{
Parent* self = static_cast<Parent*>(arg);
self->run();
}
Look at this example that I recently provided here:
/** calls thread_func in a new thread passing it user_data as argument */
thrd_hdl c_api_thread_start(void (*thread_func)(void*), void* user_data);
/** abstract thread base class
* override my_thread::run to do work in another thread
*/
class my_thread {
public:
my_thread() hdl_(c_api_thread_start(my_thread::thread_runner,this)) {}
// ...
private:
virtual int run() = 0; // we don't want this to be called from others
thrd_hdl_t hdl_; // whatever the C threading API uses as a thread handle
static int thread_runner(void* user_data)
{
my_thread* that = reinterpret_cast<my_thread*>(user_data);
try {
return that->run();
} catch(...) {
return oh_my_an_unknown_error;
}
}
};