C++ :: Overriding / Overloading New And Delete For Plugin Classes
Dec 27, 2012
I'm looking at writing my own plug-in app, but I know that deleting class instances that were created in a plug-in module can result in the dreaded "undefined behaviour" because of the different memory spaces. Many examples of plug-ins use create_class and destroy_class functions to resolve this problem, but I wondered about overriding / overloading the class's new and delete operators. This would be used for all third-party library class derivations (e.g. derived GUI classes) and all home-grown classes.
The operators would only be declared in the class declaration:
class PluginBase {
public:
void *operator new(std::size_t n);
void operator delete(void *p);
// Other plugin bits
While the actual implementation would be defined in the plug-in's implementation file:
This would need to be implemented in every transferable plug-in class (possibly by a crafty IMPLEMENT_PLUGIN(classname) macro or some other mechanism), but before I commit this to my code I was hoping for feedback. Does this sound like a good idea? The GUI classes in particular are handled by a third-party library, so it's some memory-space safe way of deleting them by the GUI library (in the app) that I'm looking for.
I'm experimenting with a custom memory-pool for my application, and I initially planned to override the global new and delete operators to allocate memory in this pool. But since I'm using QT, this will apply to all the QT-related stuff as well. Should I instead just override the new and delete operators per class?
I have a class A, from which three classes Aa Ab and Ac are inherited. In class A I have defined some functions by virtual foo()=0, which I implemented in each subclass. Each class is written in a separated .h and .cpp file.
However, now I think it is possible to overload the operator+ INSIDE each class (including pure virtual in class A), such that something like
int main() { A *value = new Aa(); A value2 = *value + 1.0f; }
This should be realizable, because the operator+ is part of the Aa class. Now, I would like to do something like
int main() { A *value = new Aa(); A value2 = 1.0f + *value; }
This time, I expect I cannot overwrite the operator+, because it is not part of either class A or class Aa.
class Var { public: Var(); ~Var(); private: QMap<QString, QSharedPointer<Data>> _mapVars; }; QDataStream &operator<<(QDataStream &stream, const QSharedPointer<Data> p_data); QDataStream &operator>>(QDataStream &stream, Data &p_data)
I want to serialize _mapVars into a file. However, I have many other classes that are derived from Data, do i need to check for Data type inside the overloaded << functions like below in order to serialize ??? This doesn';t seem to be very correct ...
S I want to have different >> operators for several derived classes. Has I tested...
Code: class base{ friend std::istream & operator>>(std::istream & in, base & v); public: base();
[Code]......
I noticed that the base operator is the only one being called for all 3 objects. which makes sense and now that I think about it I am more surprised that the "derived operators" compiled at all.
Still, how would I go about declaring different overloaded operators for the different classes?
So I'm trying to accomplish something that right seems to hard for it to be worth it. I'm trying to write a plugin framework/system for my game. I have read about it and everything that pops up says it's OS-specific and you have to load the plugins from either a .so file on linux or from a .dll file on Windows. So here lie my questions:
-Is there any universal way of accomplishing this?
-Every way I've seen assumes i know the names of the functions I'm calling which doesn't hold true if the plugin are written by a 3rd party. How would i turn the table on this matter?
I have a VC++ project to create a DLL that will be used as a Plug-in in an external programm. This DLL uses some MFC functions. The initial configuration of the project was:
-Use of MFC: Use MFC in a Static Library
-Common Language Runtime support: No Common Language Runtime support
-Runtime Library: Multi-threaded Debug (/MTd)
This configuration worked fine, there were no compilation errors and the resulting DLL worked correctly.
The problem came when it was necessary to add to the DLL some functions of .NET, using the namespace System and similar. To do that, I had to change the Common Language Runtime support, to Common Language Runtime Support (/clr). Then, when I tried to compile, I got this message:
'/MTd' and '/clr' command-line options are incompatible
So I changed the Runtime Library to Multi-threaded Debug DLL (/MDd). Then I got this error message:
Building MFC application with /MD[d] (CRT dll version) requires MFC shared dll version
So I also changed the Use of MFC to Use MFC in a Shared DLL.
After this, the compilation was correct. Then logically the size of the generated DLL is smaller, but this new DLL does not work correctly, the external program in which this DLL is used crashes.
I don't know what to do to fix the problem. Maybe I need to add some other DLLs or files to the directory where the DLL is located, where the external program uses it. But I would prefer to include a single DLL file, but this seems to be incompatible with the use of .NET functionality.
I've got the following code with output. I can't figure out myself why it's what printed out there. I believe, it has something to deal with overloading/overriding/virtual functions implementations in C++:
class Base{ public: virtual void f(int); virtual void f(double); }
[Code].....
Thus here're my conclusions: 1) in line d.f(1.0); for some reason compiler preferred casting double->int of the argument and then call to 'Derived::f(int)'.
2)in line pb->f(1.0); for some reason compiler preferred call to 'Base::f(double);'. 'Base' is static type of pb, but the dynamic type is 'Derived'.
I believe the answer has to deal with the fact whether virtual table contains in addition to functions' names also the types of arguments they accept. AFAIK, vTable doesn't include such info.
class A //parent { public: virtual void DoSomething() = 0; };
class B : public A //child { public: void DoSomething(string s) override; }
Where the child member function overrides and changes the parents member function.
I need to pass an array of key states to the Controller class' Update() function but don't want to send it to every class derived from Object (like Controller).
Is this possible or do I have to overload the original Update() member function (but I would need to define the method in Object then (i.e remove the pure virtual function (=0)))
Below is simplified code consists of two classes, namely Parent and Child.
Child is inherited from Parent.
All member functions of class Parent are declared virtual, and they have been overridden in the class Child.
Code 1:
#include <cstdlib> #include <iostream> using namespace std; #define QUANTITY 5 class Parent {
[Code] ....
The output of the code:
Child::showID() -- ID is 1804289383 Child::showID() -- ID is 846930886 Child::showID() -- ID is 1681692777 Child::showID() -- ID is 1714636915 Child::showID() -- ID is 1957747793
Parent::operator=() invoked.
Child::showID() -- ID is 1804289383 Child::showID() -- ID is 846930886 Child::showID() -- ID is 1714636915 Child::showID() -- ID is 1714636915 Child::showID() -- ID is 1957747793
Question:
Why is Parent::operator= invoked instead of Child::operator= ..?
Isn't it already declared virtual and hence would be overridden..?
I need to invoke Child::operator= instead. How to achieve this?
I have an assignment which includes overriding the prefix and postfix operators, and my teacher has provided what the output from the program should be. I've written the code and it's nearly perfect, except for one tiny error I can't seem to get right.
This is (most of) the code from the header--I left out a few of the parts that aren't relevant to my question:
Code: using namespace std; #include<string> #include<iostream> class NumDays { private: int hours;
[Code] ....
The two problem lines are supposed to be outputting 12 and 1.5, respectively, but are instead showing 13 and 1.625. I know that hours is being changed to 12 at the end of the overriden prefix operation in the line above them, so I don't understand why it returns to 13 again. What I need to change?
I create two memory manager called CMemManager1 and CMemMangaer2, using different algorithms to allocate buffer. Now I want to control which memory manager to be used, when calling new.
I try to add a parameter bUseWhichMemManager to the constructor, but in overrided new function, there are no way to access the parameter. Is there a way to pass more parameters to new operator, such as:
I have subclassed CFileDialog. I need to select both file and folder on certain case only. Suppose I have a folder selected and it is containing desired file type. Then in such situation, On clicking open button will not open the selected folder. But just close the CFileDialog with IDOK.
For doing this I need to provide my own implementation for Open button handler. I am not getting how I can do this.
I have to manage a Clinic. I need to delete a booking (for example, if John said he's coming on March 22nd at 15:30 but then he say he's not going to come, I have to delete that booking so another person can use it).
idSearched: the id of the person that is not going to come. I have a lot of specialties and each one has a list. So I ask for the speciality to delete the node (the node contains John's booking). If I don't find it, I return (-1). searchSpecByID return a pointer to the list where the speciality is. So head will point to the first node of the list. In nodeToDelete I have the node I want to delete.
The program detects OK when is the first in the list and when not, but it doesn't delete the node.
There was an "impovement" since Windows 7 in algorithm for selecting the initial directory, which is described here OPENFILENAME structure. Briefly:
Windows 7:
If lpstrInitialDir has the same value as was passed the first time the application used an Open or Save As dialog box, the path most recently selected by the user is used as the initial directory. Otherwise, if lpstrFile contains a path, that path is the initial directory.
Otherwise, if lpstrInitialDir is not NULL, it specifies the initial directory. If lpstrInitialDir is NULL and the current directory contains any files of the specified filter types, the initial directory is the current directory. Otherwise, the initial directory is the personal files directory of the current user. Otherwise, the initial directory is the Desktop folder.
The problem that this behavior is not what users of my program expect. Another constraint is that I need to use old CFileDialog dialog, not Common File Dialogs. I've tried to use advises described on StackOverflow and on MSDN. This solution by EllisMiller works perfectly:
Specifying a full path (including filename) in lpstrFile. The filename of course shows up in the filename box which is annoying. I ended up using a filename of "." and adding a bit of code to clear the filename combobox once the dialog is open.
BUT I can't figure how to clear the filename combobox. I've tried to add hook procedure, enumerate windows and clear text, but this didn't work for me. So, my question is: how can I clear text in the filename combobox of CFileDialog?
I have an array of (Student)classes created in Manager.h, which contains a new instance of class Name (name),(in Student.h)How would I go about accessing the SetFirstName method in Name.cpp if I was in a class Manager.cpp? I have tried using Students[i].name.SetFirstName("name");
// In Manager.h #include"Student.h" class Manager {
The compiler creates virtual table for the base class and also for the derived class whether we override it or not.
That means each class has separate virtual table. when we get the size of the each class with out any data members... the size of base is -- 4 bytes(64 bit) and the size of derived is -- 1
The size of base class 4 is correct since it creates the virtual pointer internally and its size is member data + virtual pointer, but it in this case I have included any data members so it has given 4 byts.
But why in case of derived is 1 byte, since it the derived class has overridden the virtual function from base, this will also contains the virtual pointer which will be pointing to derived class Vtable, it the size of the class suppose to be 4 instead of 1 byte.
In that situation, << does not call the overloaded function, but rather calls the << method defined in the i/o library, which prints a message to the controlling terminal. So once it prints the message to the terminal, it then returns the out instance. Why return the out instance rather than a boolean like true? As you can see from the example, once the message is printed to terminal, out is not used anymore.
Code: #include <iostream>#include <iomanip> using namespace std; class Score { private: // Value at which we'll shift digits from million_counter to billion_counter static const int THRESHOLD = 1000000000;
[Code] ....
It gives the errors: line 105 error: million_counter was not declared in this scope line 106 error: normalizeScore was not declared in this scope line 110 error: million_counter was not declared in this scope and more of that until line 170 error: no match for 'operator<<' in 'std:perator<< <std::char_traits<char> >((* & std::cout), ((const char*)"a+b is ")) <<operator+((*c(const Score*) (& a)), (*(const Score*)(& b)))'
I thought that because i declared friend functions, they would be able to access the private variables of the class.
I have two class GameOfLife and Cell and i want to overload square braket for class GameOfLife."if g is a GameOfLife object, g[10][5] will return the Cell at row 10 and column 5. If there is no such Cells, then it will return a new Cell with position (-1000,- 1000)."
but if g[10][1000] and 1000>cols,then it returns different Cell exp (3,2) How i do control the col ( [row][col] )?
I have a small piece of code that used the set::insert function on a set of myClass. For that, I need to overload the < and > operators, which I have, but I still get a huge error saying it can't compare.
set<MyClass> mySet; MyClass myClass
All the class information gets filled in. Then, I try to insert... mySet.insert(myClass);
bool operator<(MyClass &lhs, MyClass &rhs) { return lhs.name < rhs.name; //name is a string }
The error says ...stl_function.h:230:22: error: no match for 'operator<' in '__x < __y' MyFile.h:80:6: note: candidate is bool operator<(MyClass&, MyClass&)
Well... I observed, as a non-professional programmer that "overloading operators" has some strict rules and some conventions... so any operator can differ from another. In order to have a clearest idea, I'd like to ask you to specify, for every operator, the correct (or best) way to overload it.
There are cases where you define &operator and cases where you define operator (without "&"). There are cases where operator are defined as "friend" inside class, and other cases where operator is declared externally.
example: ostream &operator<< (why it uses & ??)
So can we have a summary for all kind of operators?
I'm trying to overload operator<<, but I get an error saying 'ostream' does not name a type. Am I forgetting to declare something else? ostream& operator<< (ostream& out, Struct &b);I made sure to #include <iostream> too.