Search Results

Search found 597 results on 24 pages for 'constructors'.

Page 4/24 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Overriding constructors

    - by demas
    Here is sample code: class One def initialize(*args) case args.size when 0 puts "one initialize" when 1 puts "one initialize #{args[0]}" end end end class Two def initialize(*args) if args.size == 2 then puts "two initialize #{args[0]} and #{args[1]}" else super(args) end end end one = One.new one = One.new("thing") two = Two.new("some", "other") two = Two.new("some") Now I'm launching the code and getting the error message: [[email protected]][~/temp]% ruby test2.rb one initialize one initialize thing two initialize some and other test2.rb:17:in `initialize': wrong number of arguments(1 for 0) (ArgumentError) from test2.rb:17:in `initialize' from test2.rb:26:in `new' from test2.rb:26:in `<main>' How can I call parent's constructor from class Two ?

    Read the article

  • C++ Allocate Memory Without Activating Constructors

    - by schnozzinkobenstein
    I'm reading in values from a file which I will store in memory as I read them in. I've read on here that the correct way to handle memory location in C++ is to always use new/delete, but if I do: DataType* foo = new DataType[sizeof(DataType) * numDataTypes]; Then that's going to call the default constructor for each instance created, and I don't want that. I was going to do this: DataType* foo; char* tempBuffer=new char[sizeof(DataType) * numDataTypes]; foo=(DataType*) tempBuffer; But I figured that would be something poo-poo'd for some kind of type-unsafeness. So what should I do? And in researching for this question now I've seen that some people are saying arrays are bad and vectors are good. I was trying to use arrays more because I thought I was being a bad boy by filling my programs with (what I thought were) slower vectors. What should I be using???

    Read the article

  • ORMs and Constructors

    - by Harper Shelby
    I'm looking over .NET ORM implementations, and I have a major burning question - are there any .NET ORM implemenations that don't require public properties for every field in the database? When I see examples like this, a little bell goes off in my head. I firmly believe in encapsulation, and being forced to open the kimono of my objects just to make them work nicely with persistence frameworks gives me the heebie-jeebies. Is this sort of accessibility required in all ORMs out there? If not, please point me to examples of those that don't need it!

    Read the article

  • Dependency injection in constructors

    - by andre
    Hello everyone. I'm starting a new project and setting up the base to work on. A few questions have risen and I'll probably be asking quite a few in here, hopefully I'll find some answers. First step is to handle dependencies for objects. I've decided to go with the dependency injection design pattern, to which I'm somewhat new, to handle all of this for the application. When actually coding it I came across a problem. If a class has multiple dependencies and you want to pass on multiple dependencies via the constructor (so that they cannot be changed after you instantiate the object). How do you do it without passing an array of dependencies, using call_user_func_array(), eval() or Reflection? This is what i'm looking for: <?php class DI { public function getClass($classname) { if(!$this->pool[$classname]) { # Load dependencies $deps = $this->loadDependencies($classname); # Here is where the magic should happen $instance = new $classname($dep1, $dep2, $dep3); # Add to pool $this->pool[$classname] = $instance; return $instance; } else { return $this->pool[$classname]; } } } Again, I would like to avoid the most costly methods to call the class. Any other suggestions?

    Read the article

  • Multiple constructors definitions with same name but different signatures (C++)

    - by PuRe_ChAoS12
    With the following code, I keep getting error C2535 when I compile. It's complaining that a member function already defined or declared. Rationnel.h ... class Rationnel { public: Rationnel(int); //Constructor Rationnel(int,int); //Constructor void add(const Rationnel); ... Rationnel.cpp ... //Constructor Rationnel::Rationnel(int n = 1) { numerateur = n; denominateur = 1; } //Constructor Rationnel::Rationnel(int n = 1, int d = 1) { numerateur = n; denominateur = d; } ... Any idea what could be causing the error? Thanks for your time.

    Read the article

  • Error handling in C++, constructors vs. regular methods

    - by Dennis Ritchie
    I have a cheesesales.txt CSV file with all of my recent cheese sales. I want to create a class CheeseSales that can do things like these: CheeseSales sales("cheesesales.txt"); //has no default constructor cout << sales.totalSales() << endl; sales.outputPieChart("piechart.pdf"); The above code assumes that no failures will happen. In reality, failures will take place. In this case, two kinds of failures could occur: Failure in the constructor: The file may not exist, may not have read-permissions, contain invalid/unparsable data, etc. Failure in the regular method: The file may already exist, there may not be write access, too little sales data available to create a pie chart, etc. My question is simply: How would you design this code to handle failures? One idea: Return a bool from the regular method indicating failure. Not sure how to deal with the constructor. How would seasoned C++ coders do these kinds of things?

    Read the article

  • Calling private constructors with Reflection.Emit?

    - by Jakob Botsch Nielsen
    I'm trying to emit the following IL: LocalBuilder pointer = il.DeclareLocal(typeof(IntPtr)); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Stloc, pointer); il.Emit(OpCodes.Ldloca, pointer); il.Emit(OpCodes.Call, typeof(IntPtr).GetMethod("ToPointer")); il.Emit(OpCodes.Ret); The delegate I bind with has the signature void* TestDelegate(IntPtr ptr) It throws the exception Operation could destabilize the runtime. Anyone knows what's wrong? EDIT: Alright, so I got the IL working now. The entire goal of this was to be able to call a private constructor. The private constructor takes a pointer so I can't use normal reflection. Now.. When I call it, I get an exception saying Attempt by method <built method> to access method <private constructor> failed. Apparently it's performing security checks - but from experience I know that Reflection is able to do private stuff like this normally, so hopefully there is a way to disable that check?

    Read the article

  • C++ using this pointer in constructors

    - by gilbertc
    In c++, during a class constructor, I started a new thread with 'this' pointer as a parameter which will be used in the thread extensively (say, calling member functions). Is that a bad thing to do? Why and what are the consequences? Thanks, Gil.

    Read the article

  • Java - Thread safety of ArrayList constructors

    - by andy boot
    I am looking at this piece of code. This constructor delegates to the native method "System.arraycopy" Is it Thread safe? And by that I mean can it ever throw a ConcurrentModificationException? public Collection<Object> getConnections(Collection<Object> someCollection) { return new ArrayList<Object>(someCollection); } Does it make any difference if the collection being copied is ThreadSafe eg a CopyOnWriteArrayList? public Collection<Object> getConnections(CopyOnWriteArrayList<Object> someCollection) { return new ArrayList<Object>(someCollection); }

    Read the article

  • Are protected constructors considered good practice?

    - by Álvaro G. Vicario
    I'm writing some little helper classes to handle trees. Basically, I have a node and a special root node that represents the tree. I want to keep it generic and simple. This is part of the code: <?php class Tree extends TreeNode{ public function addById($node_id, $parent_id, $generic_content){ if( $parent = $this->findNodeById($parent_id) ){ $parent->addChildById($node_id, $generic_content); } } } class TreeNode{ public function __construct($node_id, $parent_id, $generic_content){ // ... } protected function addChildById($node_id, $generic_content){ $this->children[] = new TreeNode($this->node_id, $node_id, $generic_content); } } $Categories = new Tree; $Categories->addById(1, NULL, $foo); $Categories->addById(2, NULL, $bar); $Categories->addById(3, 1, $gee); ?> My questions: Is it sensible to force TreeNode instances to be created through TreeNode::addById()? If it's so, would it be good practise to declare TreeNode::__construct() as private/protected?

    Read the article

  • Constructors for C++ objects

    - by sasquatch
    I have class Person as following : class Person { char* name; int age; }; Now I need to add two contructors. One taking no arguments, that inserts field values to dynamically allocated resources. Second taking (char*, int) arguments initialized by initialization list. Last part is to define a destructor showing information about destroying objects and deallocating dynamically allocated resources. How to perform this task ? That's what I already have : class Person { char* name; int age; public: Person(){ this->name = new *char; this->age = new int; } Person(char* c, int i){ } };

    Read the article

  • JavaScript - Inheritance in Constructors

    - by j0ker
    For a JavaScript project we want to introduce object inheritance to decrease code duplication. However, I cannot quite get it working the way I want and need some help. We use the module pattern. Suppose there is a super element: a.namespace('a.elements.Element'); a.elements.Element = (function() { // public API -- constructor Element = function(properties) { this.id = properties.id; }; // public API -- prototype Element.prototype = { getID: function() { return this.id; } }; return Element; }()); And an element inheriting from this super element: a.namespace('a.elements.SubElement'); a.elements.SubElement = (function() { // public API -- constructor SubElement = function(properties) { // inheritance happens here // ??? this.color = properties.color; this.bogus = this.id + 1; }; // public API -- prototype SubElement.prototype = { getColor: function() { return this.color; } }; return SubElement; }()); You will notice that I'm not quite sure how to implement the inheritance itself. In the constructor I have to be able to pass the parameter to the super object constructor and create a super element that is then used to create the inherited one. I need a (comfortable) possibility to access the properties of the super object within the constructor of the new object. Ideally I could operate on the super object as if it was part of the new object. I also want to be able to create a new SubElement and call getID() on it. What I want to accomplish seems like the traditional class based inheritance. However, I'd like to do it using prototypal inheritance since that's the JavaScript way. Is that even doable? Thanks in advance! EDIT: Fixed usage of private variables as suggested in the comments. EDIT2: Another change of the code: It's important that id is accessible from the constructor of SubElement.

    Read the article

  • Constructors with inheritance in c++

    - by Crystal
    If you have 3 classes, with the parent class listed first shape- 2d shapes, 3d shapes - circle, sphere When you write your constructor for the circle class, would you ever just initialize the parent Shape object and then your current object, skipping the middle class. It seems to me you could have x,y coordinates for Shape and initialize those in the constructor, and initialize a radius in the circle or sphere class, but in 2d or 3d shape classes, I wouldn't know what to put in the constructor since it seems like it would be identical to shape. So is something like this valid Circle::Circle(int x, int y, int r) : Shape(x, y), r(r) {} I get a compile error of: illegal member initialization: 'Shape' is not a base or member So I wasn't sure if my code was legal or best practice even. Or if instead you'd have the middle class just do what the top level Shape class does TwoDimensionalShape::TwoDimensionalShape(int x, int y) : Shape (x, y) {} and then in the Circle class Circle::Circle(int x, int y, int r) : TwoDimensionalShape(x, y), r(r) {}

    Read the article

  • Calling constructors in c++ without new

    - by Nils
    I've often seen that people create objects in C++ using Thing myThing("asdf"); Instead of Thing myThing = myThing("asdf"); This seems to work (using gcc), at least as long as there are no templates involved. My question now, is the first line correct and if so should I use it?

    Read the article

  • C++ allocate objects on heap of base class with protected constructors via inheritance

    - by KRao
    I have a class with protected constructor: class B { protected: B(){}; }; Now I derive from it and define two static functions and I manage to actually create objects of the class B, but not on the heap: class A : public B { public: static B createOnStack() {return B();} //static B* createOnHeap() {return new B;} //Compile time Error on VS2010 }; B b = A::createOnStack(); //This works on VS2010! The question is: 1) Is VS2010 wrong in allowing the first case? 2) Is it possible to create objects of B without modifying B in any way (no friendship and no extra functions). I am asking, because it is possible to make something similar when dealing with instances of B and its member functions, see: http://accu.org/index.php/journals/296 Thank you in advance for any suggestion! Kind regards

    Read the article

  • JavaScript constructors inside a namespace

    - by Joe
    I have read that creating a namespace for JavaScript projects helps to reduce conflicts with other libraries. I have some code with a lot of different types of objects for which I have defined constructor functions. Is it good practice to put these inside the namespace as well? For example: var shapes = { Rectangle: function(w, h) { this.width = w; this.height = h; } }; which can be called via: var square = new shapes.Rectangle(10,10);

    Read the article

  • Constructors in Inner classes (implementing Interfaces)

    - by thepandaatemyface
    Hi, How would I go about writing a constructor for an inner class which is implementing an interface? I know I could make a whole new class, but I figure there's got to be a way to do something along the line of this: JButton b = new JButton(new AbstractAction() { public AbstractAction() { super("This is a button"); } public void actionPerformed(ActionEvent e) { System.out.println("button clicked"); } }); When I enter this it doesn't recognize the AbstractAction method as a constructor (compiler asks for return type). Anyone have an idea? Thanks

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >