I began writing code assuming that:  person1 = person    will give me a new instance, it doesn't. person1 is actually a reference/pointer to person.  person = {age : 2}  person1 = person;  person.age = 3;  alert(person1.age); //gives us 3.   How do I make a new instance without changing much code around? I have like 300 lines of code inside the object, functions(methods?) and everything. Wouldn't want to rewrite as a constructor.
912
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but . I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.  I've also seen recursive copying functions with various flaws.  I'm surprised no canonical solution exists.
90115
I am trying to create an array of pointers. These pointers will point to a Student object that I created. How do I do it? What I have now is:   Student * db = new Student[5];   But each element in that array is the student object, not a pointer to the student object. Thanks.
29117
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.  First I tried this example in the console:  a = b = {}; a.foo = 'bar'; console.log(b.foo);   The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.  a = b = 'foo'; a = 'bar'; console.log(b);   That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.  Why does this happen?  N.B. This example could be simplified even more with the following code:    a = {}; b = a; a.foo = 'bar'; console.log(b.foo);  a = 'foo'; b = a; a = 'bar'; console.log(b);     (I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
13958
As a  developer I'm used to running through constructors:    class Test {     public Test() {         DoSomething();     }      public Test(int count) : this() {         DoSomethingWithCount(count);     }      public Test(int count, string name) : this(count) {         DoSomethingWithName(name);     } }   Is there a way to do this in C++?  I tried calling the Class name and using the 'this' keyword, but both fail.
93507
In C#, is there a way to instantiate an instance of a class without invoking its constructor?  Assume the class is public and is defined in a 3rd party library and the constructor is internal.  The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.  NOTE: I specifically do not want to call any constructor so using reflection to access the internal constructor is not an option.
51358
How do you decide between passing arguments to a method versus simply declaring them as object instance variables that are visible to all of the object's methods? I prefer keeping instance variables in a list at the end of the Class, but this list gets longer as my program grows. I figure if a variable is passed often enough it should just be visible to all methods that need it, but then I wonder, &quot;if everything is public there will be no need for passing anything at all!&quot;
3879
So I was playing around a little more with attributes in .NET, and realized that every call to Type.GetCustomAttributes() creates a new instance of my attribute. Why is that? I would think that the attribute instance would basically be a singleton-per-MemberInfo, with 1 instance bound to the Type, PropertyInfo, etc...  Here is my test code:  using System;  namespace AttribTest { [AttributeUsage(AttributeTargets.Class)] class MyAttribAttribute : Attribute {     public string Value { get; set; }      public MyAttribAttribute()         : base()     {         Console.WriteLine("Created MyAttrib instance");     } }  [MyAttrib(Value = "SetOnClass")] class MyClass { }  class Program {     static void Main(string[] args)     {         Console.WriteLine("Getting attributes for MyClass.");         object[] a = typeof(MyClass).GetCustomAttributes(false);         ((MyAttribAttribute)a[0]).Value = "a1";          Console.WriteLine("Getting attributes for MyClass.");         a = typeof(MyClass).GetCustomAttributes(false);         Console.WriteLine(((MyAttribAttribute)a[0]).Value);          Console.ReadKey();     } } }   Now if I were to implement attributes, I would expect the output to be:  Created MyAttrib instance Getting attributes for MyClass. Getting attributes for MyClass. a1   Where the "class loader" (sorry, I have more of a Java background, not 100% sure how .net loads its types) would compile MyClass, and create an instance of MyAttribAttribute, and store them together somewhere. (probably the Perm Gen in the heap if this were Java) The 2 calls to GetCustomAttributes() would then just return the same earlier created instance.  But the actual output is:  Getting attributes for MyClass. Created MyAttrib instance Getting attributes for MyClass. Created MyAttrib instance SetOnClass   So... why? It seems like creating a new instance of all these objects for every call is a bit excessive, and not good for performance/memory management.  Is there any way to always get the same instance over and over?  Anyone have any ideas why it was designed this way?  The reason I care at all is because I made a custom attribute that internally holds some validation information, so in the Attribute I basically have a "private bool Validated" that I set to true. The validation stuff takes a while, so I don't want to run it every time. Now the problem is that since it creates a new instance of the attribute each time I get the attributes, Validated is always "false".
30376
Let's say you have a class called Customer, which contains the following fields:   UserName Email First Name Last Name   Let's also say that according to your business logic, all Customer objects must have these four properties defined.  Now, we can do this pretty easily by forcing the constructor to specify each of these properties.  But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object.    I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them.  But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.  Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
92846
I just learned about the C++ construct called "placement new".  It allows you to exactly control where a pointer points to in memory.  It looks like this:   #include &lt;new&gt;        // Must #include this to use "placement new"  #include "Fred.h"     // Declaration of class Fred   void someCode()  {    char memory[sizeof(Fred)];    void* place = memory;     Fred* f = new(place) Fred();   // Create a pointer to a Fred(),                                   // stored at "place"     // The pointers f and place will be equal     ...  }    (example from ) In this example, the this pointer of Fred will be equal to place.    I've seen it used in our team's code once or twice.  In your experience, what does this construct enable?  Do other pointer languages have similar constructs?  To me, it seems reminiscent of equivalence in FORTRAN, which allows disparate variables to occupy the same location in memory.
72809
When you create an instance of a class with the new operator, memory gets allocated on the heap. When you create an instance of a struct with the new operator where does the memory get allocated, on the heap or on the stack ?
77567
I've read in the  and the  the mention of inner classes. What is their purpose?  I see in the Apex Workbook that they used private variables and setter/getter methods in the inner class, but why didn't they just do that in the outer class with a constructer, getter, and setter?
8134
The  says that public class SomeObject {   public void SomeOperation()   {     lock(this)     {       //Access instance variables     }   } }  is &quot;a problem if the instance can be accessed publicly&quot;. I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?
80428
I have a class like this:  public class myClass {   public List&lt;myOtherClass&gt; anewlist = new List&lt;myOtherClass&gt;;    public void addToList(myOtherClass tmp)   {     anewList.Add(tmp);   }  }   So I call "addToList" a hundred times, each adding a unique item to the list.  I've tested my items to show that before I run the "addToList" method, they are unique.  I even put a line in to test "tmp" to make sure it was what I was expecting.  However, when I do this (lets say myClass object is called tmpClass):  int i = tmpClass.anewList.Count(); for (int j = 0; j&lt;i; j++) {    //write out each member of the list based on index j... }   I get the same exact item, and it's the last one that was written into my list.  It's as if when I add, I'm overwriting the entire list with the last item I've added.    Help?  This makes no sense. I've also tried List.Insert, where I'm always inserting at the end or at index 0.  Still no dice.  Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements.  :)  UPDATE: Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {         Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena    Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {     Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output...  I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena
13003
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.  function foo(id) {     this.dom = document.getElementById(id);     this.bar = 5;     var self = this;     this.dom.addEventListener("click", self.onclick, false); }  foo.prototype = {     onclick : function() {         this.bar = 7;     } };   Now when I create a new object (after the DOM has loaded, with a span#test)  var x = new foo('test');   The 'this' inside the onclick function points to the span#test and not the foo object.  How do I get a reference to my foo object inside the onclick function?
38591
class someclass {};  class base {     int a;     int *pint;     someclass objsomeclass;     someclass* psomeclass; public:     base()     {         objsomeclass = someclass();         psomeclass = new someclass();         pint = new int();          throw "constructor failed";         a = 43;     } }  int main() {     base temp(); }   In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?  int main() {     base *temp = new base(); }   How about in the above code? How can the memory leaks be avoided after the constructor throws?
6356
I have 2 objects from the same type and i would like to shallow copy one state to the other. In C++ i have memcpy which is great. How can i do it in C#? The MemberwiseClone() is not good enough because it creates &amp; returns a new object and i like to copy to an existing object. I thought of using reflection but i'm afraid it will be too slow for production code. I also thought of using one of the .Net serializers but i think they also create object rather than setting an existing one.  My Use Case:  I have a template object (class not struct) which needs to be updated by one of its instances (objects made of this template)  Any ideas?