Can I call a function from the base class which return bool from derived class - c++11

I have the following base class:
class node_layer_manager_t : public layer_manager_t
{
protected:
//Devices
trx_t trx;
private:
std::vector<string> trx_dump_labels;
public:
node_layer_manager_t( xml::node_t& params );
~node_layer_manager_t();
virtual bool set_profile(void) override;
}
I created the following derived class:
class node_layer_manager_with_rad_t : public node_layer_manager_t
{
protected:
//Devices
radio_t radio;
public:
node_layer_manager_with_rad_t(xml::node_t& params );
~node_layer_manager_with_rad_t();
virtual bool set_profile(void) override;
virtual void radio_monitoring_job_function(void);
intervalues_t<double> radio_tmp;
ushort duration_seconds_for_radio_monitoring;
};
I want it so that the set profile will execute the set_profile of the base class and in addition some other action.
Can I just write it this way?
bool node_layer_manager_with_rad_t::set_profile(void)
{
bool success;
node_layer_manager_t::set_profile();
try
{
string_t profile_tag = "logs/trx_dump/node:"+get_id();
dev_tx = profile->get_decendant(profile_tag.c_str());
cout<<"sarit id= "<< get_id()<<endl;
success = true;
}
catch(...)
{
cout<<"sarit profile error: "<<endl;
success = false;
}
return success; //**
}
**Or should I reurn the follwing:
return (success && node_layer_manager_t::set_profile());

If you have to call parent set_profile regardless what you have to do in derived class, you should adopt design which take care about this constraint.
Typically, you should mark based class set_porfile as final and manage call of a dedicated derived class method inside based class:
class node_layer_manager_t : public layer_manager_t
{
protected:
....
// set_profile actions of derived class
// proposed a default without side effect implementation if
// derived class doesn't need to overload this.
virtual bool set_profile_child() { return true; };
private:
....
public:
.....
// Manage here call of derived
virtual bool set_profile() override final
{
// actions before derived specific actions
....
// Call specific derived class actions
bool success = set_profile_child();
// actions after derived specific actions
if (success)
{
//do based class action
}
return success;
}
}
and in child:
class node_layer_manager_with_rad_t : public node_layer_manager_t
{
protected:
....
public:
virtual bool set_profile_child() override;
};
// Manage only there own action, regardless of needs of based class
bool node_layer_manager_with_rad_t::set_profile(void)
{
try
{
// Do what you're in charge, and only what you're in charge!
}
catch(...)
{
cout<<"sarit profile error: "<<endl;
success = false;
}
return success; //**
}
With this kind of design, each class do only what it have to manage, and only its. Derived class doesn't have to deal with needs of based class.
If you want to offer to your derived class ability to decided if code is executed before or after generic behavior, you can replace or add to set_profile_child() two methods: bool pre_set_profile() and bool post_set_profile()

At first, you haven't declared success anywhere (so actually, this is not a mcve, the code should not compile as is).
Still I get it - and tThe answer is: it depends on what you actually want to do...
Do you want to call the super class first or after the sub class code? Your example implies the former, your alternative the latter. Do you want to abort if the super class function fails or still execute your code?
Your inital example calls the super class function, ignores the result and does its own stuff afterwards.
This calls the super class function first and continues only on success:
bool success = node_layer_manager_t::set_profile();
if(success)
{
try { /*...*/ } // <- no need to set success to true, it is already
catch(...) { /*...*/ success = false; }
}
This executes both, but combines the result:
bool success = node_layer_manager_t::set_profile();
try { /*...*/ } // <- do not modify success, must remain false if super class failed!
catch(...) { /*...*/ success = false; }
Your alternative hints to executing the sub class code first and only call the super class function, if nothing went wrong.
Any of these approaches might be appropriate, none of them might be. You have to get a clear image of what your requirements are - and then implement the code such that your needs are satisfied...

Related

Calling parent struct inherited methods

I have a struct A that inherits from other classes (which I'm not allowed to change). Inside A and it's methods I can call inherited methods (lets say A_method(int i), for example) without problem but when I tried to write a nested struct (lets say In) and call A_method(int i) and there is were I'm stuck.
The initial code looks like this, and I can't change it, is some kind of college assigment.
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
virtual void play () {
}
};
RegisterPlayer(PLAYER_NAME);
Then I tried this:
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
//My code
struct In {
int x;
void do_smthing() {
A_method(x);
}
}
virtual void play () {
}
};
RegisterPlayer(PLAYER_NAME);
Ok, from a beginning I knew I could't do this, for In to see it's parent class it should have a pointer to it but In is a often instantiated object in my code and I wanted to avoid passing this constantly to a constructor so I tried this aproach:
#include "Player.hh"
struct A : public Player {
static Player* factory () {
return new A;
}
//My code
static struct Aux
A* ptr;
Aux(A* _p) { ptr = _p; }
} aux;
struct In {
int x;
void do_smthing() {
aux.ptr->A_method(x);
}
}
virtual void play () {
//the idea is to call do_smthing() here.
}
};
RegisterPlayer(PLAYER_NAME);
What I want to avoid (if possible) is something like this:
struct In {
int x;
A* ptr;
In (A* _p) : ptr(_p) {}
void do_smthing() {
ptr->A_method(x);
}
}
The main reason for this: I have more struct definitions and they they are instantiated multiple times through the rest of the (omitted) code, and I don't like the idea of seeing In(this) so many times.
I don't know if I'm completly missing something or what I want to do it's just not possible... Please ask for clarifications if necessary.
(Also, performance is kind of critical, my code will be tested with limited CPU time so I kinda have to avoid expensive approachs if possible. Using C++11)
There is no way you can skip passing the this pointer. Instead, you could create a helper function in A:
template <typename InnerType, typename ...Params>
InnerType makeInner(Params&&... params)
{
return InnerType(this, std::forward<Params>(params)...);
}
Then you can use
auto * a = A::factory();
auto inner = a->makeInner<A::In>();
I have some suggestions which are not directly related to you question but may help:
A::facotry() returns a std::unique_ptr<A> instead of raw pointer
Try to describe what problem you are trying to solve. I have a strong feeling that there can be a better design other than creating many nested structs.
I don't see passing a this pointer could have any impact on the performance. The more important thing is to identify the path that is latency-sensitive and move expensive operations out of those paths.

How to check record in c# 9 in NET 5 is immutable at runtime

Record is a new feature in c#9, Net 5
It's said
If you want the whole object to be immutable and behave like a value, then you should consider declaring it as a record
Creating a record in c#9 , NET 5:
public record Rectangle
{
public int Width { get; init; }
public int Height { get; init; }
}
Then instantiating it:
var rectangle = new Rectangle (20,30);
Trying to change the value:
rectange.Width=50; //compiler error
Compiler raise the error:
error CS8852: Init-only property or indexer 'Rectangle.Width' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
That is right and insure that the record is immutable.
Using a method like to test IsImmutable type give false, because in record there is no generated readonly properties.
How to check the record in c# 9, Net 5 is immutable at runtime or even it has init property?
A record is indeed mutable at runtime. This is intentional, is it means most serializer frameworks work without updating.
It is however possible to check if a property is initonly by checking:
public static bool IsInitOnly(PropertyInfo propertyInfo)
{
return propertyInfo?.SetMethod.ReturnParameter
.GetRequiredCustomModifiers()
.Any(x => x.FullName == _isExternalInitName)
?? false;
}
private static string _isExternalInitName =
typeof(System.Runtime.CompilerServices.IsExternalInit).FullName;
I don't think that it's possible to check for immutability at runtime.
Here's some of the generated code for your record. You can see that both properties have a public setter.
public class Rectangle : IEquatable<Rectangle>
{
[CompilerGenerated]
private readonly int <Width>k__BackingField;
[CompilerGenerated]
private readonly int <Height>k__BackingField;
protected virtual Type EqualityContract
{
[CompilerGenerated]
get
{
return typeof(Rectangle);
}
}
public int Width
{
[CompilerGenerated]
get
{
return <Width>k__BackingField;
}
[CompilerGenerated]
set
{
<Width>k__BackingField = value;
}
}
public int Height
{
[CompilerGenerated]
get
{
return <Height>k__BackingField;
}
[CompilerGenerated]
set
{
<Height>k__BackingField = value;
}
}
The following code will compile and run without errors.
var rect = new Rectangle { Height = 1, Width = 2 };
typeof(Rectangle).GetProperty("Height").SetValue(rect, 5);
Console.Write(rect.Height);
//Prints 5
At runtime the init accessor is just a regular setter. It's only at compile time that a check is made to only allow init accessor to be called during object initialization.
So I don't see any way to check at runtime that Rectangle is immutable.

Actual function call count doesn't match EXPECT_CALL(mockImplClass, receive(_, _))

I am facing problem while running gtest for the following code sample.
ignore header includes as its compilable and running fine.
Error:
GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: receive(0x7ffcee4fc990, 0x7ffcee4fc900)
Returns: 0
NOTE: You can safely ignore the above warning unless this call should not happen. Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call. See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#knowing-when-to-expect for details.
/data/home/sipadhy/unit_test_research/gTest/ImplClassTest.cpp:174: Failure
Actual function call count doesn't match EXPECT_CALL(mockImplClass, receive(_, _))...
Expected: to be called at least once
Actual: never called - unsatisfied and active
Sample Code:
// Main Class where function to be mocked
class ImplClass
{
public:
virtual int receive(structX* x, structY* y){ // some logic }
};
// An intermidiate class which calls the main class
class IntermidiateClass
{
std::shared_ptr<ImplClass> implClassPtr = nullptr;
public:
setImplClassptr(std::shared_ptr<ImplClass> ptr)
{
implClassPtr = ptr;
}
int getValue()
{
structX x;
structY y;
return(implClassPtr->receive(x, y));
}
};
// Mock Class
class MockImplClass: public ImplClass
{
public:
MOCK_METHOD2(receive, int(structX, structY));
}
// Test case
TEST(MyTest, TEST1)
{
MockImplClass mockImplClass;
IntermidiateClass intermidiateObj;
intermidiateObj.setImplClassptr(std::make_shared<MockImplClass>());
EXPECT_CALL(mockImplClass, receive(_, _))
.Times(AtLeast(1))
.WillRepeatedly(Return(1));
int retVal = intermidiateObj.getValue();
}
Thanks,
Siva
You create a brand new object of the MockImplClass class here:
std::make_shared<MockImplClass>()
Thus your first created object
MockImplClass mockImplClass;
never gets used to call receive()

Class method callbacks in D to C functions

I'm writing a simple, lightweight engine in D. For the input calls I use GLFW3. The library in question uses callbacks to send input events to the program.
What I would like is to use a method from a class as the callback function, rather than a function. This is proving difficult (just as it is in C++). I believe there is an elegant way to do it, but this is how I got it right now.
public void initialise(string logPath) {
[...]
m_Window = new RenderWindow();
m_Window.create();
// Lets set up the input loop.
GLFWkeyfun keyCB = function(GLFWwindow* win, int key, int scancode, int action, int mods) {
printf("Got key event: %d:%d:%d:%d\n");
RenderWindow rw = Root().getRenderWindow();
switch (key) {
case KeyboardKeyID.Q:
glfwSetWindowShouldClose(win, true);
break;
case KeyboardKeyID.H:
if (rw.hidden) {
rw.show();
} else {
rw.hide();
}
break;
default:
break;
}
};
glfwSetKeyCallback(m_Window.window, keyCB);
}
Here is the definition of the callback setting function and type:
extern (C) {
alias GLFWkeyfun = void function(GLFWwindow*, int, int, int, int);
GLFWkeyfun glfwSetKeyCallback(GLFWwindow*, GLFWkeyfun);
}
What I would like to do instead, is create a method that is part of the class. Is there any way to do this?
A solution I tried was a static method wrapped around in extern (C), this worked for calling it, but then I could (obviously) not access this or any other methods, which defeats the point of the exercise.
Thanks in advance.
The way I'd do it is to have a static map of the pointers to the class, so like:
static YourWindowClass[GLFWwindow*] mappings;
Then, in the constructor, once you get a GLFWwindow pointer, add it right in:
mappings[m_Window.window] = this;
Now, make the static extern(C) function to use as the callback. When it gets a pointer from C, look up your class reference in that mappings array and then go ahead and call the member function through that, forwarding the arguments.
So a bit of an extra step, but since it doesn't look like the callback lets you pass user-defined data to it (BTW, attention all lib writers: user-defined void* to the callbacks is sooooo useful, you should do it whenever possible!), but since it doesn't do that the associative array is the next best thing.
Well, I have figured it out my own. The solution I went with was a Singleton class InputManager. Instances of RenderWindow attach themselves to it with the following function. The InputManager then creates an anonymous function() for the RenderWindow that receives events, which then calls a function that handles the actual event.
The idea is then that listeners attach themselves to the InputManager and receive keyboard events for the RenderWindow they requested.
class InputManager {
private static InputManager m_Instance;
private RenderWindow[] m_Watched;
private KeyboardListener[][RenderWindow] m_KeyListeners;
public void recvKeyEvent(GLFWwindow* w, int k, int c, int a, int m) {
writeln("Received key: ", k);
}
public void watch(RenderWindow win) {
if (!isWatched(win)) {
// Relay the key callbacks onto the InputManager.
GLFWkeyfun keyCB = function(GLFWwindow* w, int k, int c, int a, int m) {
InputManager().recvKeyEvent(w, k, c, a, m);
};
glfwSetKeyCallback(win.window, keyCB);
}
}
private bool isWatched(RenderWindow win) {
foreach(RenderWindow w; m_Watched) {
if (win == w) {
return true;
}
}
return false;
}
public static InputManager opCall() {
if (m_Instance is null) {
m_Instance = new InputManager();
}
return m_Instance;
}
private this() {
// nothing
}
}
Works like a charm, now to figure out how to properly attach listeners elegantly.
For those curious, the full source code with how this is set up can be found at https://github.com/Adel92/Mage2D. I hope it helps someone else in a similar position with callbacks.

Proper way of raising events from C++/CLI?

I was wondering what's the proper way of raising events from C++/CLI. In C# one should first make a copy of the handler, check if it's not null, and then call it. Is there a similar practice for C++/CLI?
This isn't the whole story! You don't usually have to worry about null event handlers in C++/CLI. The code for these checks is generated for you. Consider the following trivial C++/CLI class.
public ref class MyClass
{
public:
event System::EventHandler ^ MyEvent;
};
If you compile this class, and disassemble it using Reflector, you get the following c# code.
public class MyClass
{
// Fields
private EventHandler <backing_store>MyEvent;
// Events
public event EventHandler MyEvent
{
[MethodImpl(MethodImplOptions.Synchronized)] add
{
this.<backing_store>MyEvent = (EventHandler) Delegate.Combine(this.<backing_store>MyEvent, value);
}
[MethodImpl(MethodImplOptions.Synchronized)] remove
{
this.<backing_store>MyEvent = (EventHandler) Delegate.Remove(this.<backing_store>MyEvent, value);
}
raise
{
EventHandler <tmp> = null;
<tmp> = this.<backing_store>MyEvent;
if (<tmp> != null)
{
<tmp>(value0, value1);
}
}
}
}
The usual checks are being done in the raise method. Unless you really want custom behavior, you should feel comfortable declaring your event as in the above class, and raising it without fear of a null handler.
C++/CLI allows you to override raise in custom event handlers so you don't have to test for null or copy when raising the event. Of course, inside your custom raise you still have to do this.
Example, adapted from the MSDN for correctness:
public delegate void f(int);
public ref struct E {
f ^ _E;
public:
void handler(int i) {
System::Console::WriteLine(i);
}
E() {
_E = nullptr;
}
event f^ Event {
void add(f ^ d) {
_E += d;
}
void remove(f ^ d) {
_E -= d;
}
void raise(int i) {
f^ tmp = _E;
if (tmp) {
tmp->Invoke(i);
}
}
}
static void Go() {
E^ pE = gcnew E;
pE->Event += gcnew f(pE, &E::handler);
pE->Event(17);
}
};
int main() {
E::Go();
}
If your issue is that raise isn't private, then explicitly implement it like the docs say:
http://msdn.microsoft.com/en-us/library/5f3csfsa.aspx
In summary:
If you just use the event keyword, you create a "trivial" event. The compiler generates add/remove/raise and the delegate member for you. The generated raise function (as the docs say) checks for nullptr. Trivial events are documented here:
http://msdn.microsoft.com/en-us/library/4b612y2s.aspx
If you want "more control", for example to make raise private, then you have to explicitly implement the members as shown in the link. You must explicitly declare a data member for the delegate type. Then you use the event keyword to declare the event-related members, as in the Microsoft example:
// event keyword introduces the scope wherein I'm defining the required methods
// "f" is my delegate type
// "Event" is the unrealistic name of the event itself
event f^ Event
{
// add is public (because the event block is public)
// "_E" is the private delegate data member of type "f"
void add(f ^ d) { _E += d; }
// making remove private
private:
void remove(f ^ d) { _E -= d; }
// making raise protected
protected:
void raise(int i)
{
// check for nullptr
if (_E)
{
_E->Invoke(i);
}
}
}// end event block
Wordy, but there it is.
-reilly.

Resources