how to add a function to a lib class without overriding it - c++

I've a case in which I need to add some functions to a game engine class I'm using for a VR project without overriding the class it self:
The engine class name is AnnwaynPlayer that contains many useful methods to control the player, now I'm in the networking phase so I need to add 2 extra methods to this lib class which are setActive() and setConnected(), what is the best way to do this ?

If you can't touch the class itself then you probably want to use inheritance. This is one of the main goals of object-oriented programming -- to be able to add/change the behavior of an existing class without altering it. So you want something like:
class MyAnnwaynPlayer : public AnnwaynPlayer {
public:
void setActive();
void setConnected();
// ...
}
Now, things will be fine if AnnwaynPlayer has a virtual destructor. If it doesn't and your MyAnnwaynPlayer class has a non-trivial destructor then you have to wary of using an instance of MyAnnwaynPlayer through a pointer (be it raw or smart) of base class AnnwaynPlayer. When a pointer of the type is deleted, it will not chain through a call to your MyAnnwaynPlayer destructor.

Also consider ADL if you only need access to the public API of the base class. It's safer than inheritance, because you don't necessarily know the right class to inherit from in cases where the implementation returns something ultimately unspecified (like an internal derived class).
In essence, this would look like this:
namespace AnnwaynNamespace {
void setActive(AnnwaynPlayer& p);
void setConnected(AnnwaynPlayer& p);
};
And you could call them without using those functions (or the namespace), because ADL.
void wherever(AnnwaynNamespace::AnnwaynPlayer& p) {
setActive(p);
}
So setActive, etc, become part of the actual public API of the class, without involving any inheritance.

Related

Custom function per-instance of a class (C++)

I have a class "EngineObject"
I would like to have a custom function for that class which may vary by instance of that object.
Right now i'm doing it with function pointers like this:
class EngineObject{
public:
bool (*Update)(EngineObject* Me);
bool (*Prep)(EngineObject* Me);
bool (*OnCollide)(EngineObject* Me, EngineObject* Them);
};
As you may have noticed, this requires me to do something quite atrocious. I have to feed the object to its member function... Digusting
it also requires me to write extra getters and setters that I really don't want to be accessible from any other part of the code, just so I can see the "innards" of the EngineObject from functions passed in via function pointer
Is there some way I could write a function that I could apply, per instance of the object, that could access the privates of the object, and without having to pass the object to the function?
FOR CLARITY:
Let's say I want two EngineObjects
EngineObject1 = new EngineObject();
EngineObject2 = new EngineObject();
I'd like to set the update function of 1 to (something) and 2 to (something else)
EngineObject1.Update = &foo;
EngineObject2.Update = &bar;
I cannot simply use virtual functions and inheritance because these functions need to be able to be assigned and re-assigned at run-time.
The problem is that I need access to privates from these functions, and in order to do that i'd need to write public getters and setters for everything, which sort of erases the need for making anything private...
context:
The reason i'm doing this is to allow dynamic type generation at run time without introspection, to maximize what can be done from a scripting interface, and reduce the total number of functions that need to be bound to the scripting interface and reduce the learning curve for users.
Basically, you'd have an EngineObjectTemplate class which specified what all these functions would be for this dynamically generated type, and then the EngineObject would be created using a function in the EngineObjectTemplate class
EngineObjectTemplates may be generated at run time by combining various pre-written C++ functions (Update, Prep, OnCollide). This would be a "type" of sorts.
If a user wishes to write a new update, prep, or oncollide function, they could choose to write and compile it into a DLL file and add it to the project (Which my EXE will read and add to a list of function pointers, which can be referenced by string names in the scripting language to assign to templates and/or therefore engineobjects), or they could script it in the scripting language I choose, which would of course be slower.
Another reason why i'm doing it this way is that i'd like to avoid inheritance because it is HELL to make inherited classes work with the scripting wrapper I plan on using.
What you want to do is not possible because what you are actually asking is essentially:
"How can I make code living outside of a class access private members".
If this was possible without jumping through some ugly, ugly hoops, then it would mean that private is broken.
The only way to access private members of a class is that the class explicitly gives you access to them, either from its interface, or by marking the code as friend as part of its declaration.
Either the members are private, or they are not. You can't have it both ways.
N.B. This is a bit of a lie, as you can do some tricks in some exceptional corner-cases, but these should only be used as a last resort.
You can create a callable object class that overrides the () operator. A base class would provide the template for what the replaceable function receives as parameters with child classes implementing that particular method. Then you declare the callable class as a friend to your owning class. Like the following:
class EngineObject;
class Callable;
class EngineObject
{
private:
int member;
Callable *func;
public:
EngineObject(int m, Callable *f) : member(m), func(f) {}
int Call(int p)
{
return func(p);
}
friend Callable;
};
class Callable;
{
public:
int operator(EngineObject *eo, int param)
{
eo->member = param;
return param;
}
};
In the above, I also further hid the variable function call behind a wrapper so that an outside function doesn't need to pass the object as a parameter as well.

Ways to make (relatively) safe assumptions about the type of concrete subclasses?

I have an interface (defined as a abstract base class) that looks like this:
class AbstractInterface
{
public:
virtual bool IsRelatedTo(const AbstractInterface& other) const = 0;
}
And I have an implementation of this (constructors etc omitted):
class ConcreteThing
{
public:
virtual bool IsRelatedTo(const AbstractInterface& other) const
{
return m_ImplObject.has_relationship_to(other.m_ImplObject);
}
private:
ImplementationObject m_ImplObject;
}
The AbstractInterface forms an interface in Project A, and the ConcreteThing lives in Project B as an implementation of that interface. This is so that code in Project A can access data from Project B without having a direct dependency on it - Project B just has to implement the correct interface.
Obviously the line in the body of the IsRelatedTo function cannot compile - that instance of ConcreteThing has an m_ImplObject member, but it can't assume that all AbstractInterfaces do, including the other argument.
In my system, I can actually assume that all implementations of AbstractInterface are instances of ConcreteThing (or subclasses thereof), but I'd prefer not to be casting the object to the concrete type in order to get at the private member, or encoding that assumption in a way that will crash without a diagnostic later if this assumption ceases to hold true.
I cannot modify ImplementationObject, but I can modify AbstractInterface and ConcreteThing. I also cannot use the standard RTTI mechanism for checking a type prior to casting, or use dynamic_cast for a similar purpose.
I have a feeling that I might be able to overload IsRelatedTo with a ConcreteThing argument, but I'm not sure how to call it via the base IsRelatedTo(AbstractInterface) method. It wouldn't get called automatically as it's not a strict reimplementation of that method.
Is there a pattern for doing what I want here, allowing me to implement the IsRelatedTo function via ImplementationObject::has_relationship_to(ImplementationObject), without risky casts?
(Also, I couldn't think of a good question title - please change it if you have a better one.)

Can someone explain the benefits of polymorphism?

So I understand pretty much how it works, but I just can't grasp what makes it useful. You still have to define all the separate functions, you still have to create an instance of each object, so why not just call the function from that object vs creating the object, creating a pointer to the parent object and passing the derived objects reference, just to call a function? I don't understand the benefits of taking this extra step.
Why do this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
Parent* bar = &foo;
bar->function();
return -3234324;
}
vs this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
foo.function();
return -3234324;
}
They do exactly the same thing right? Only one uses more memory and more confusion as far as I can tell.
Both your examples do the same thing but in different ways.
The first example calls function() by using Static binding while the second calls it using Dynamic Binding.
In first case the compiler precisely knows which function to call at compilation time itself, while in second case the decision as to which function should be called is made at run-time depending on the type of object which is pointed by the Base class pointer.
What is the advantage?
The advantage is more generic and loosely coupled code.
Imagine a class hierarchy as follows:
The calling code which uses these classes, will be like:
Shape *basep[] = { &line_obj, &tri_obj,
&rect_obj, &cir_obj};
for (i = 0; i < NO_PICTURES; i++)
basep[i] -> Draw ();
Where, line_obj, tri_obj etc are objects of the concrete Shape classes Line, Triangle and so on, and they are stored in a array of pointers of the type of more generalized base class Shape.
This gives the additional flexibility and loose coupling that if you need to add another concrete shape class say Rhombus, the calling code does not have to change much, because it refers to all concrete shapes with a pointer to Base class Shape. You only have to make the Base class pointer point to the new concrete class.
At the sametime the calling code can call appropriate methods of those classes because the Draw() method would be virtual in these classes and the method to call will be decided at run-time depending on what object the base class pointer points to.
The above is an good example of applying Open Closed Principle of the famous SOLID design principles.
Say you want someone to show up for work. You don't know whether they need to take a car, take a bus, walk, or what. You just want them to show up for work. With polymorphism, you just tell them to show up for work and they do. Without polymorphism, you have to figure out how they need to get to work and direct them to that process.
Now say some people start taking a Segway to work. Without polymorphism, every piece of code that tells someone to come to work has to learn this new way to get to work and how to figure out who gets to work that way and how to tell them to do it. With polymorphism, you put that code in one place, in the implementation of the Segway-rider, and all the code that tells people to go to work tells Segway-riders to take their Segways, even though it has no idea that this is what it's doing.
There are many real-world programming analogies. Say you need to tell someone that there's a problem they need to investigate. Their preferred contact mechanism might be email, or it might be an instant message. Maybe it's an SMS message. With a polymorphic notification method, you can add a new notification mechanism without having to change every bit of code that might ever need to use it.
polymorphism is great if you have a list/array of object which share a common ancestor and you wich to do some common thing with them, or you have an overridden method. The example I learnt the concept from, use shapes as and overriding the draw method. They all do different things, but they're all a 'shape' and can all be drawn. Your example doesn't really do anything useful to warrant using polymorphism
A good example of useful polymorphism is the .NET Stream class. It has many implementations such as "FileStream", "MemoryStream", "GZipStream", etcetera. An algorithm that uses "Stream" instead of "FileStream" can be reused on any of the other stream types with little or no modification.
There are countless examples of nice uses of polymorphism. Consider as an example a class that represents GUI widgets. The most base classs would have something like:
class BaseWidget
{
...
virtual void draw() = 0;
...
};
That is a pure virtual function. It means that ALL the class that inherit the Base will need to implement it. And ofcourse all widgets in a GUI need to draw themselves, right? So that's why you would need a base class with all of the functions that are common for all GUI widgets to be defined as pure virtuals because then in any child you will do like that:
class ChildWidget
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
class ChildWidget2
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
Then in your code you need not care about checking what kind of widget it is that you are drawing. The responsibility of knowing how to draw itself lies with the widget (the object) and not with you. So you can do something like that in your main loop:
for(int i = 0; i < numberOfWidgets; i++)
{
widgetsArray[i].draw();
}
And the above would draw all the widgets no matter if they are of ChildWidget1, ChildWidget2, TextBox, Button type.
Hope that it helps to understand the benefits of polymorphism a bit.
Reuse, generalisation and extensibility.
I may have an abstract class hierarchy like this: Vehicle > Car. I can then simply derive from Car to implement concrete types SaloonCar, CoupeCar etc. I implement common code in the abstract base classes. I may have also built some other code that is coupled with Car. My SaloonCar and CoupeCar are both Cars so I can pass them to this client code without alteration.
Now consider that I may have an interface; IInternalCombustionEngine and a class coupled with with this, say Garage (contrived I know, stay with me). I can implement this interface on classes defined in separate class hierarchies. E.G.
public abstract class Vehicle {..}
public abstract class Bus : Vehicle, IPassengerVehicle, IHydrogenPowerSource, IElectricMotor {..}
public abstract class Car : Vehicle {..}
public class FordCortina : Car, IInternalCombustionEngine, IPassengerVehicle {..}
public class FormulaOneCar : Car, IInternalCombustionEngine {..}
public abstract class PowerTool {..}
public class ChainSaw : PowerTool, IInternalCombustionEngine {..}
public class DomesticDrill : PowerTool, IElectricMotor {..}
So, I can now state that an object instance of FordCortina is a Vehicle, it's a Car, it's an IInternalCombustionEngine (ok contrived again, but you get the point) and it's also a passenger vehicle. This is a powerful construct.
The poly in polymorphic means more than one. In other words, polymorphism is not relevant unless there is more than one derived function.
In this example, I have two derived functions. One of them is selected based on the mode variable. Notice that the agnostic_function() doesn't know which one was selected. Nevertheless, it calls the correct version of function().
So the point of polymorphism is that most of your code doesn't need to know which derived class is being used. The specific selection of which class to instantiate can be localized to a single point in the code. This makes the code much cleaner and easier to develop and maintain.
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void function() const {};
};
class Derived1 : public Parent
{
void function() const { cout << "derived1"; }
};
class Derived2 : public Parent
{
void function() const { cout << "derived2"; }
};
void agnostic_function( Parent const & bar )
{
bar.function();
}
int main()
{
int mode = 1;
agnostic_function
(
(mode==1)
? static_cast<Parent const &>(Derived1())
: static_cast<Parent const &>(Derived2())
);
}
Polymorphism is One of the principles OOP. With polymorphism you can choose several behavior in runtime. In your sample, you have a implementation of Parent, if you have more implementation, you can choose one by parameters in runtime. polymorphism help for decoupling layers of application. in your sample of third part use this structers then it see Parent interface only and don't know implementation in runtime so third party independ of implementations of Parent interface. You can see Dependency Injection pattern also for better desing.
Just one more point to add. Polymorphism is required to implement run-time plug-ins. It is possible to add functionality to a program at run-time. In C++, the derived classes can be implemented as shared object libraries. The run time system can be programmed to look at a library directory, and if a new shared object appears, it links it in and can start to call it. This can also be done in Python.
Let's say that my School class has a educate() method. This method accepts only people who can learn. They have different styles of learning. Someone grasps, someone just mugs it up, etc.
Now lets say I have boys, girls, dogs, and cats around the School class. If School wants to educate them, I would have to write different methods for the different objects, under School.
Instead, the different people Objects (boys,girls , cats..) implement the Ilearnable interface. Then, the School class does not have to worry about what it has to educate.
School will just have to write a
public void Educate (ILearnable anyone)
method.
I have written cats and dogs because they might want to visit different type of school. As long as it is certain type of school (PetSchool : School) and they can Learn, they can be educated.
So it saves multiple methods that have the same implementation but different input types
The implementation matches the real life scenes and so it's easy for design purposes
We can concentrate on part of the class and ignore everything else.
Extension of the class (e.g. After years of education you come to know, hey, all those people around the School must go through GoGreen program where everyone must plant a tree in the same way. Here if you had a base class of all those people as abstract LivingBeings, we can add a method to call PlantTree and write code in PlantTree. Nobody needs to write code in their Class body as they inherit from the LivingBeings class, and just typecasting them to PlantTree will make sure they can plant trees).

How do I add code automatically to a derived function in C++

I have code that's meant to manage operations on both a networked client and a server, since there is significant overlap between the two. However, there are a few functions here and there that are meant to be exclusively called by the client or server, and accidentally calling a client function on the server (or vice versa) is a significant source of bugs.
To reduce these sorts of programming errors, I'm trying to tag functions so that they'll raise a ruckus if they're misused. My current solution is a simple macro at the start of each function that calls an assert if the client or server accesses members they shouldn't. However, this runs into problems when there are multiple derived instances of classes, in that I have to tag the implementation as client or server side in EVERY child class.
What I'd like to be able to do is put a tag in the virtual member's signature in the base class, so that I only have to tag it once and not run into errors by forgetting to do it repeatedly. I've considered putting a check in a base class implementation and then referring to it with something like base::functionName, but that runs into the same issue as far as needing to manually add the function call to every implementation. Ideally, I'd be able to have parent versions of the function called automatically like default constructors do.
Does anybody know how to achieve something like this in C++? Is there an alternate approach I should be considering?
Thanks!
Another approach might be to override a different method than the one your callers actually call:
class Base {
public:
void doit(const Something &);
protected:
virtual void real_doit(const Something &);
};
class Derived: public Base {
protected:
virtual void real_doit(const Something &);
};
The implementation of Base::doit() could do the check to make sure that it's being called in the right environment, and then call the virtual real_doit() function. Derived classes would override the protected virtual function, and users of either class wouldn't be able to call the protected function.
The Base::doit() function is not virtual so that derived classes can't accidentally override the wrong one. (People can try, but hopefully they'll notice soon enough when it's not called.)
What you've proposed is incredibly complex. It sounds like a simpler solution would be
class CommonStuff {
// all common code that anybody can safely call
};
class ServerBase : public CommonStuff {
// only what the server is allowed to call; can safely be overwritten
};
class ClientBase : public CommonStuff {
// only what the client is allowed to call; can safely be overwritten
};
Compile-time enforcements are much better than any sort of runtime enforcement.
There's not a way within the language (that I know of) to do what you're asking without redesigning your classes. The simplest solution may be to have a Client interface (pure virtual) class that does not declare server functions, and a Server interface class that doesn't declare client functions, and have your consolidated code inherit (publicly) from both interfaces. Then in your client program, use a reference (or pointer) to the Client interface, which does not allow access to any methods not declared in the Client interface. On the server, use the Server interface.
This will also allow you to use derived classes as Server or Client as well.
I would consider splitting this library into three libraries: A base library that has most everything, a server-only library, and a client-only library. As long as the client doesn't use the server library, you're good. You may end up adding a few extra classes (class Processor might split into BaseProcessor, ClientProcessor, and ServerProcessor, where each subclass has one additional function that the base doesn't.)
If that won't work, could you put the server/client check in the class constructor, and call the assertion there? (That would only work if the server-only or client-only is granular to the class, not to the method.)
If that won't work, would it make any sense to actually compile different versions of your library, based on whether it's a server or client build? Surround the methods, and their declarations, with #ifdef SERVERBUILD and #ifdef CLIENTBUILD, and include some checks to make sure they aren't both defined (#if defined(SERVERBUILD) && defined(CLIENTBUILD), #error Can't define both!).
I voted up Greg Hewgill's answer, but it got me thinking about ways to add "aspects" such as you request. I used his naming convention here (class Base and method doit):
class Base {
protected:
class Aspect {
public:
Aspect(int x) {
std::cout << "aspect" << std::endl;
}
};
public:
virtual void doit(const Something &arg, const Aspect hook = 0)
{
std::cout << "doit(" << arg << ")" << std::endl;
}
};
Callers can just say base.doit(arg) since Aspect is a default argument. Its constructor runs before doit and its destructor (not pictured) runs after. Sadly my first idea to make the default argument hook = this is not allowed.
Children can override doit with the same signature and get the same effect.

extend a abstract base class w/o source recompilation?

ignore this, i thought of a workaround involving header generation. It isnt the nicest solution but it works. This question is to weird to understand. Basically i want to call a virtual function that hasnt been declared in the lib or dll and use it as normal (but have it not implemented/empty func).
I have an abstract base class in my library. All my plugins inherit from it, the user plugin inherits from this class and his application uses this class as a plugin pointer. I want that user to be able to extend the class and add his functions. The problem is, I am sure if he adds a virtual function and try to call it, the code will crash due to my objects not having the extra data in its vtable. How can I work around that? I thought of inheriting it but that would lead to ugly problems when a 3rd user comes to play. I dont want him to typecast to send the extended functions.
I was thinking of a msg function like intptr_t sendMsg(enum msgName, void* argv); But that removes the safty and I'd need to typecast everything. Whats the best solution for this? I would much rather use vtables then use a sendMsg function. How can I work around this?
Are you asking if you can add virtual functions to the base class without recompiling? The short answer to that is "no". The long answer is in your question, you'd have to provide some kind of generic "call_func" interface that would allow you to call functions "dynamically".
I think you can use register and callback mechanism
Your plugin can provide
Abstract base class "Base" and function
Register(Base *);
Now client can call plugin Register function
Register(b);
where b is defined as
Base *b = new Derived;
where Derived is new class derived from Base
I am not 100% sure I see the problem.
If the user1 derived type extends your base class (with more virtual methods) then that should be fine (of course your code will never know or understand these new methods but presumably you would not be calling them:
class B
{
virtual void doStuff() { /* Nothing */}
};
// User 1 version:
class U1: public B
{
virtual void doStuff()
{
this->doA();
this->doB();
}
virtual void doA() {}
virtual void doB() {}
};
// User 2 version can extend it differently.
Note:
If you are worried by slicing because you are storing objects in a vector that is a slightly different problem.
std::vector<B> objs;
objs.push_back(U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));
Here the problem is that a user defined type U1 can not be copied into the vector because the vector holds only B objects. This slices off the extra data held in U1.
The solution to this problem is that you need to hold pointers in the vector. This of course leads to other problems with exception safety. So boost has the ptr_vector<> container to hold objects correctly but still let them be used like objects.
#include <boost/ptr_container/ptr_vector.hpp>
......
boost::ptr_vector<B> objs;
objs.push_back(new U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));