To illustrate the question, let's imagine a dummy example where we have this function from an external API:  // This function is run in a separated thread void Transfert(string source, string destination, void (*callbackFunction)(int)) {     for(int i = 0; i &lt; 100; i++)     {         // Simulation of a file transfert         // ...         //           // We call the callback function to update the progression of the file transfert         callbackFunction(i);     } }   I want to use this function to transfert a file and follow the progress with the help of the callback function. Here is my code:  // Class containing information about the transfert class FileTransfert { public:     FileTransfert(string, string);     void MyCallback(int);      // Those members are public to simplify this example but should be private     long m_progress;     string m_source;     string m_destination; };  FileTransfert::FileTransfert(string source, string destination) {     m_source = source;     m_destination = destination; }  // Used to update the progress variable void FileTransfert::MyCallback(int progress) {     m_progress = progress; }  int main(int argc, char* argv[]) {     FileTransfert f("source.txt", "destination.txt");      // It's a new thread     Transfert(f.m_source, f.m_destination, f.MyCallback); // Compilation error      // Now I want to follow the transfer with the m_progress variable      return 0; }   My class FileTransfert has a m_progress member and I would like to refresh it during the file transfert. So I create a callback function who updates m_progress. The problem is I cannot use a method of an object as a callback function.  So, here is my question : how can I modify my code to follow the progression of the transfert?I have some constraints : I have to call Transfert from a function who is outside the FileTransfert class and the m_progress variable has to be inside the FileTransfert class. In other words, I can't change all the architecture of my code.  Important note: I can't change the code and the signature of the Transfert function. In the answers of those two questions ( and ), we change the signature of the function but I can't in my case.    EDIT  As I said in comments, there is no proper solution to this problem if I can't change the signature of the Transfert function. One idea is to use global variables but it can be very risky in a multithread environment.
5040
I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors.   Here is what I did from my constructor:  m_cRedundencyManager-&gt;Init(this-&gt;RedundencyManagerCallBack);   This doesn't compile - I get the following error:      Error  8 error C3867: 'CLoggersInfra::RedundencyManagerCallBack': function call missing argument list; use '&amp;CLoggersInfra::RedundencyManagerCallBack' to create a pointer to member   I tried the suggestion to use &amp;CLoggersInfra::RedundencyManagerCallBack - didn't work for me.   Any suggestions/explanation for this??  I'm using VS2008.  Thanks!!
124139
I have a class which has many small functions. By small functions, I mean functions that doesn't do any processing but just return a literal value. Something like:  string Foo::method() const{     return "A"; }   I have created a header file "Foo.h" and source file "Foo.cpp". But since the function is very small, I am thinking about putting it in the header file itself. I have the following questions:   Is there any performance or other issues if I put these function definition in header file? I will have many functions like this. My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?
14927
Disclaimer Yes, I am fully aware that what I am asking about is totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot.  I'm mainly looking to see if can be done. Now that that's out of the way, is there any way to access private class members in C++ from outside the class?  For example, is there any way to do this with pointer offsets? (Naive and otherwise non-production-ready techniques welcome) Update As noted in the comments, I asked this question because I wanted to write a blog post on over-encapsulation (and how it affects TDD).  I wanted to see if there was a way to say &quot;using private variables isn't a 100% reliable way to enforce encapsulation, even in C++.&quot;  At the end, I decided to focus more on how to solve the problem rather than why it's a problem, so I didn't feature some of the stuff brought up here as prominently as I had planned, but I still left a link. At any rate, if anyone's interested in how it came out, here it is:   (I suggest reading it before you decide that I'm crazy).
28494
I have an apex class which fetches and upserts data from external source to Salesforce. Below is the batch class: global class PolicyCalloutBatchClass implements Database.Batchable&lt;Integer&gt;,Database.AllowsCallouts, Database.Stateful {     global Iterable&lt;Integer&gt; start(Database.BatchableContext context) {         Integer[] values = new Integer[0];         while(values.size() &lt; 2999 || Test.isRunningTest()) values.add(values.size());         return values;     }     global void execute(Database.BatchableContext context, Integer[] values) {                  HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();         JsonParser objJsonParser = (JsonParser) JSON.deserialize(policyresponse, JsonParser.class);                    JsonParser.cls_value clsValue = objJsonParser.value;         Map&lt;String, JsonParser.cls_data&gt; clsDataMap = new Map&lt;String, JsonParser.cls_data&gt;();         for(JsonParser.cls_data objClsData: clsValue.data){             clsDataMap.put(objClsData.id, objClsData);         }         list&lt;Policy__c&gt; updatelist = new list&lt;Policy__c&gt;();         for (String eachIdFromMap : clsDataMap.keySet()){                          Policy__c policy = new Policy__c(                 unique_id__c = clsDataMap.get(eachIdFromMap).id,                 agent_id__c = clsDataMap.get(eachIdFromMap).agentId);             updatelist.add(policy);           }         try{             upsert updatelist unique_id__c;             }         catch(DmlException e){             system.debug('This class didnt compile');         }     }     global void finish(Database.BatchableContext context) {              } }  Below is my Mock test class: @isTest global class MockHttpResponseGenerator implements HttpCalloutMock {     // Implement this interface method     global HTTPResponse respond(HTTPRequest req) {           HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();                         return policyres;     } }  Below is my test class: @isTest  private class PolicyUpdateController_Test {     static testMethod void testPostCallout() {         Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());                    Test.startTest();       Database.executeBatch(new PolicyCalloutBatchClass(), 50);          Test.stopTest();              } }  Now, when I run the above test class, either the test class runs forever without any output or I could see the error as  System.LimitException: Too many callouts: 101  Can anyone please let me know if there is any way to get this done? Thanks!
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.
93759
I have  a  requirement where a future method need to be called from batch apex ,I came across various articles stating that a future method could not be called from the batch. Is there any alternate solutions for that?
110516
I am trying to perform two operations. First I want to increase the size of a GameObject and then delay for 0.1s before returning it back to its original size. However, when I try using StartCoroutine(), it keeps giving me the error :  An object reference is required to access not-static members   even though I made my Delay() function static. Can somebody please tell me what I'm doing wrong?  public static void MoveSelected(int choice) {     GameObject rock1 = GameObject.Find("Rock1");     GameObject paper1 = GameObject.Find("Paper1");     GameObject scissors1 = GameObject.Find("Scissors1");      Vector3 scl;      if (choice == 1)     {         scl = rock1.transform.localScale;         scl.x *= 1.1f;         scl.y *= 1.1f;         rock1.transform.localScale = scl;          StartCoroutine(Delay());          scl.x /= 1.1f;         scl.y /= 1.1f;         rock1.transform.localScale = scl;     }     else if (choice == 2)     {         scl = paper1.transform.localScale;         scl.x *= 1.1f;         scl.y *= 1.1f;         paper1.transform.localScale = scl;          StartCoroutine(Delay());          scl.x /= 1.1f;         scl.y /= 1.1f;         rock1.transform.localScale = scl;     }     else if (choice == 3)     {         scl = scissors1.transform.localScale;         scl.x *= 1.1f;         scl.y *= 1.1f;         scissors1.transform.localScale = scl;          StartCoroutine(Delay());          scl.x /= 1.1f;         scl.y /= 1.1f;         rock1.transform.localScale = scl;     }  }  static IEnumerator Delay() {     yield return new WaitForSeconds(0.1f); }
15717
I'd like to do something like this:  &gt;&gt; foo = @() functionCall1() functionCall2()   So that when I said:  &gt;&gt; foo()   It would execute functionCall1() and then execute functionCall2().  (I feel that I need something like the )  EDIT:  functionCall1 and functionCall2 are not necessarily functions that return values.
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
29305
What does it mean to extend a function? Can someone please give an example?  Thanks in advance!
13449
I can't understand where the final keyword is really handy when it is used on method parameters.    If we exclude the usage of anonymous classes, readability and intent declaration then it seems almost worthless to me.   Enforcing that some data remains constant is not as strong as it seems.    If the parameter is a primitive then it will have no effect since the parameter is passed to the method as a value and changing it will have no effect outside the scope.  If we are passing a parameter by reference, then the reference itself is a local variable and if the reference is changed from within the method, that would not have any effect from outside of the method scope.    Consider the simple test example below. This test passes although the method changed the value of the reference given to it, it has no effect.  public void testNullify() {     Collection&lt;Integer&gt; c  = new ArrayList&lt;Integer&gt;();           nullify(c);     assertNotNull(c);            final Collection&lt;Integer&gt; c1 = c;     assertTrue(c1.equals(c));     change(c);     assertTrue(c1.equals(c)); }  private void change(Collection&lt;Integer&gt; c) {     c = new ArrayList&lt;Integer&gt;(); }  public void nullify(Collection&lt;?&gt; t) {     t = null; }
42622
We all know what virtual functions are in C++, but how are they implemented at a deep level?  Can the vtable be modified or even directly accessed at runtime?  Does the vtable exist for all classes, or only those that have at least one virtual function?   Do abstract classes simply have a NULL for the function pointer of at least one entry?  Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual?  And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
111110
I'm a bit confused as to how to get two method to call each other (i.e., have A() call B() and B() call A()). It seems that F# only 'sees' the method after it's been encountered in code, so if it hasn't, it just says value or constructor has not been defined.  Am I missing something very basic here?
18490
Can someone provide a simple explanation of methods vs. functions in OOP context?
106358
Most of what I have read about retry operations is that they are vaguely complicated and indepth. I have written the code below which seems to accomplish this without too much confusion - I'm wondering if there are any pitfalls I am not seeing here.   The class uses a top-level schedulable class, which calls a queueable class to make the callout, and if the callout is unsuccessful, it just schedules the top level class again five minutes later. After testing it appears this works indefinitely.   A simple string token, assigned at the first invocation, is also passed between the classes, and I have tested and found that the token does persist, even when runs are scheduled for a later time.   Thanks for helpful thoughts!  public class SelfServe implements Schedulable {      public String Token = null;      public void execute(SchedulableContext ctx) {                  RetrieveMachineDetails Job = new RetrieveMachineDetails();             Job.Token = Token;             System.enqueueJob(Job);      }           public class RetrieveMachineDetails implements Queueable, Database.AllowsCallouts {          public String Token = null;          public void execute(QueueableContext context){                                            Http http = new Http();             HttpRequest request = new HttpRequest();                             request.setEndpoint('https://app.endpoint.com/api');                     request.setMethod('POST');                     request.setHeader('Content-Type', 'application/json;charset=UTF-8');                                      request.setBody('{"query":  "$message_=\'METRIC\' &amp;&amp; $tier=\'customer\' "}');                                                                                                                                                                                    HttpResponse response = http.send(request);                            if (response.getStatusCode() == 200) {                 //do stuff                  }              else { //retry                  DateTime Dt = system.now().addMinutes(5);                                String day = string.valueOf(Dt.day());                                        String month = string.valueOf(Dt.month());                                          String hour = string.valueOf(Dt.hour());                                       String minute = string.valueOf(Dt.minute());                                                       String year = string.valueOf(Dt.year());                                   String ScheduledTime = '0 ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ?' + ' ' + year;                  SelfServe Job = new SelfServe();                     Job.Token = Token;                 System.schedule('SelfServe Job'+Dt, ScheduledTime, Job);              }         }        }  }
13904
I'm doing some architectural cleanup that involves moving a bunch of classes into different projects and/or namespaces. Currently I'm moving the files by hand, building, and then manually adding using Foo statements as needed to resolve compilation errors. Anyone know of a smarter way of doing this? (We're a CodeRush and Refactor! shop, but I'd be interested to hear if Resharper has support for this)
65261
What are some real world places that call for delegates?  I'm curious what situations or patterns are present where this method is the best solution.  No code required.