Search Results

Search found 3493 results on 140 pages for 'constructor'.

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

  • Constructor Overloading

    - by Mark Baker
    Normally when I want to create a class constructor that accepts different types of parameters, I'll use a kludgy overloading principle of not defining any args in the constructor definition: e.g. for an ECEF coordinate class constructor, I want it to accept either $x, $y and $z arguments, or to accept a single array argument containg x, y and z values, or to accept a single LatLong object I'd create a constructor looking something like: function __construct() { // Identify if any arguments have been passed to the constructor if (func_num_args() > 0) { $args = func_get_args(); // Identify the overload constructor required, based on the datatype of the first argument $argType = gettype($args[0]); switch($argType) { case 'array' : // Array of Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromArray'; break; case 'object' : // A LatLong object that needs converting to Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromLatLong'; break; default : // Individual Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromXYZ'; break; } // Call the appropriate overload constructor call_user_func_array(array($this,$overloadConstructor),$args); } } // function __construct() I'm looking at an alternative: to provide a straight constructor with $x, $y and $z as defined arguments, and to provide static methods of createECEFfromArray() and createECEFfromLatLong() that handle all the necessary extraction of x, y and z; then create a new ECEF object using the standard constructor, and return that Which option is cleaner from an OO purists perspective?

    Read the article

  • How do I get a PHP class constructor to call its parent's parent's constructor

    - by Paulo
    I need to have a class constructor in PHP call its parent's parent's (grandparent?) constructor without calling the parent constructor. // main class that everything inherits class Grandpa { public function __construct() { } } class Papa extends Grandpa { public function __construct() { // call Grandpa's constructor parent::__construct(); } } class Kiddo extends Papa { public function __construct() { // THIS IS WHERE I NEED TO CALL GRANDPA'S // CONSTRUCTOR AND NOT PAPA'S } } I know this is a bizarre thing to do and I'm attempting to find a means that doesn't smell bad but nonetheless, I'm curious if it's possible. EDIT I thought I should post the rationale for the chosen answer. The reason being; it most elegant solutionto the problem of wanting to call the "grandparent's" constructor while retaining all the values. It's certainly not the best approach nor is it OOP friendly, but that's not what the question was asking. For anyone coming across this question at a later date - Please find another solution. I was able to find a much better approach that didn't wreak havoc on the class structure. So should you.

    Read the article

  • Constructor with less arguments from a constructor

    - by mike_hornbeck
    I have Constructor Tree(int a, int b, int c) and second Constructor Tree(int a, int b, int c, String s). How to load second constructor from first just to save writing all the logics ? I thought about something like this but it gives me 'null' object. public Tree(int a, int b, int c){ Tree t1 = new Tree(a, b, c, "randomString"); }

    Read the article

  • Constructor within a constructor

    - by Chiramisu
    Is this a bad idea? Does calling a generic private constructor within a public constructor create multiple instances, or is this a valid way of initializing class variables? Private Class MyClass Dim _msg As String Sub New(ByVal name As String) Me.New() 'Do stuff End Sub Sub New(ByVal name As String, ByVal age As Integer) Me.New() 'Do stuff End Sub Private Sub New() 'Initializer constructor Me._msg = "Hello StackOverflow" 'Initialize other variables End Sub End Class

    Read the article

  • Constructor overloading in Java - best practice

    - by errr
    There are a few topics similar to this, but I couldn't find one with a sufficient answer. I would like to know what is the best practice for constructor overloading in Java. I already have my own thoughts on the subject, but I'd like to hear more advice. I'm referring to both constructor overloading in a simple class and constructor overloading while inheriting an already overloaded class (meaning the base class has overloaded constructors). Thanks :)

    Read the article

  • Super constructor must be a first statement in Java constructor [closed]

    - by Val
    I know the answer: "we need rules to prevent shooting into your own foot". Ok, I make millions of programming mistakes every day. To be prevented, we need one simple rule: prohibit all JLS and do not use Java. If we explain everything by "not shooting your foot", this is reasonable. But there is not much reason is such reason. When I programmed in Delphy, I always wanted the compiler to check me if I read uninitializable. I have discovered myself that is is stupid to read uncertain variable because it leads unpredictable result and is errorenous obviously. By just looking at the code I could see if there is an error. I wished if compiler could do this job. It is also a reliable signal of programming error if function does not return any value. But I never wanted it do enforce me the super constructor first. Why? You say that constructors just initialize fields. Super fields are derived; extra fields are introduced. From the goal point of view, it does not matter in which order you initialize the variables. I have studied parallel architectures and can say that all the fields can even be assigned in parallel... What? Do you want to use the unitialized fields? Stupid people always want to take away our freedoms and break the JLS rules the God gives to us! Please, policeman, take away that person! Where do I say so? I'm just saying only about initializing/assigning, not using the fields. Java compiler already defends me from the mistake of accessing notinitialized. Some cases sneak but this example shows how this stupid rule does not save us from the read-accessing incompletely initialized in construction: public class BadSuper { String field; public String toString() { return "field = " + field; } public BadSuper(String val) { field = val; // yea, superfirst does not protect from accessing // inconstructed subclass fields. Subclass constr // must be called before super()! System.err.println(this); } } public class BadPost extends BadSuper { Object o; public BadPost(Object o) { super("str"); this. o = o; } public String toString() { // superconstructor will boom here, because o is not initialized! return super.toString() + ", obj = " + o.toString(); } public static void main(String[] args) { new BadSuper("test 1"); new BadPost(new Object()); } } It shows that actually, subfields have to be inilialized before the supreclass! Meantime, java requirement "saves" us from writing specializing the class by specializing what the super constructor argument is, public class MyKryo extends Kryo { class MyClassResolver extends DefaultClassResolver { public Registration register(Registration registration) { System.out.println(MyKryo.this.getDepth()); return super.register(registration); } } MyKryo() { // cannot instantiate MyClassResolver in super super(new MyClassResolver(), new MapReferenceResolver()); } } Try to make it compilable. It is always pain. Especially, when you cannot assign the argument later. Initialization order is not important for initialization in general. I could understand that you should not use super methods before initializing super. But, the requirement for super to be the first statement is different. It only saves you from the code that does useful things simply. I do not see how this adds safety. Actually, safety is degraded because we need to use ugly workarounds. Doing post-initialization, outside the constructors also degrades safety (otherwise, why do we need constructors?) and defeats the java final safety reenforcer. To conclude Reading not initialized is a bug. Initialization order is not important from the computer science point of view. Doing initalization or computations in different order is not a bug. Reenforcing read-access to not initialized is good but compilers fail to detect all such bugs Making super the first does not solve the problem as it "Prevents" shooting into right things but not into the foot It requires to invent workarounds, where, because of complexity of analysis, it is easier to shoot into the foot doing post-initialization outside the constructors degrades safety (otherwise, why do we need constructors?) and that degrade safety by defeating final access modifier When there was java forum alive, java bigots attecked me for these thoughts. Particularly, they dislaked that fields can be initialized in parallel, saying that natural development ensures correctness. When I replied that you could use an advanced engineering to create a human right away, without "developing" any ape first, and it still be an ape, they stopped to listen me. Cos modern technology cannot afford it. Ok, Take something simpler. How do you produce a Renault? Should you construct an Automobile first? No, you start by producing a Renault and, once completed, you'll see that this is an automobile. So, the requirement to produce fields in "natural order" is unnatural. In case of alarmclock or armchair, which are still chair and clock, you may need first develop the base (clock and chair) and then add extra. So, I can have examples where superfields must be initialized first and, oppositely, when they need to be initialized later. The order does not exist in advance. So, the compiler cannot be aware of the proper order. Only programmer/constructor knows is. Compiler should not take more responsibility and enforce the wrong order onto programmer. Saying that I cannot initialize some fields because I did not ininialized the others is like "you cannot initialize the thing because it is not initialized". This is a kind of argument we have. So, to conclude once more, the feature that "protects" me from doing things in simple and right way in order to enforce something that does not add noticeably to the bug elimination at that is a strongly negative thing and it pisses me off, altogether with the all the arguments to support it I've seen so far. It is "a conceptual question about software development" Should there be the requirement to call super() first or not. I do not know. If you do or have an idea, you have place to answer. I think that I have provided enough arguments against this feature. Lets appreciate the ones who benefit form it. Let it just be something more than simple abstract and stupid "write your own language" or "protection" kind of argument. Why do we need it in the language that I am going to develop?

    Read the article

  • Visibility of reintroduced constructor

    - by avenmore
    I have reintroduced the form constructor in a base form, but if I override the original constructor in a descendant form, the reintroduced constructor is no longer visible. type TfrmA = class(TForm) private FWndParent: HWnd; public constructor Create(AOwner: TComponent; const AWndParent: Hwnd); reintroduce; overload; virtual; end; constructor TfrmA.Create(AOwner: TComponent; const AWndParent: Hwnd); begin FWndParent := AWndParent; inherited Create(AOwner); end; type TfrmB = class(TfrmA) private public end; type TfrmC = class(TfrmB) private public constructor Create(AOwner: TComponent); override; end; constructor TfrmC.Create(AOwner: TComponent); begin inherited Create(AOwner); end; When creating: frmA := TfrmA.Create(nil, 0); frmB := TfrmB.Create(nil, 0); frmC := TfrmC.Create(nil, 0); // Compiler error My work-around is to override the reintroduced constructor or to declare the original constructor overloaded, but I'd like to understand the reason for this behavior. type TfrmA = class(TForm) private FWndParent: HWnd; public constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; const AWndParent: Hwnd); reintroduce; overload; virtual; end; type TfrmC = class(TfrmB) private public constructor Create(AOwner: TComponent; const AWndParent: Hwnd); override; end;

    Read the article

  • Private constructor and public parameter constructor -C#

    - by Amutha
    I heard that private constructor prevent object creation from outside world. When i have a code public class Product { public string Name { get;set;} public double Price {get;set;} Product() { } public Product(string _name,double _price) { } } here still i can declare public constructor(parameter),won't it spoil the purpose of private constructor? When do we need both private and public constructor(parameter) in code? I need detailed explanation please.

    Read the article

  • Opt-out of copy constructor

    - by sheepsimulator
    This might be a silly question, but... I've been writing a number of classes that utilize non-copyable members. These classes are never initialized via the copy constructor in my source. When I try to compile without supplying my own copy-constructor, g++ throws out many errors about how it can't build a default copy constructor, due to the non-copyable member objects. Is there a way to tell the compiler to just not give me a copy constructor?

    Read the article

  • Empty constructor or no constructor

    - by Ram
    Hi, I think it is not mandatory to have a default constructor in a class (C#). So in that situation shall I have a empty constructor in the class or I can skip it? Is it a best practice to have a default empty constructor? Class test { test() { } ...... } or Class test { ...... }

    Read the article

  • testing if constructor in constructor chain

    - by Delan Azabani
    I'm attempting to implement a GTK+ inspired widget toolkit for the web in JavaScript. One of the constructor chains goes gtk.widget => gtk.container => gtk.bin => gtk.window Every gtk.widget has a showAll method, which, if and only if the widget is a gtk.container or derivative (such as gtk.bin or gtk.window), will recursively show the children of that widget. Obviously, if it isn't a gtk.container or derivative, we shouldn't do anything because the widget in question can't contain anything. For reference, here is my inheritance function; it's probably not the best, but it's a start: function inherit(target, parent) { target.prototype = new parent; target.prototype.constructor = target; } I know that I can check for the direct constructor like this: if (this.constructor === gtk.container) ... However, this only tests for direct construction and not, say, if the object is a gtk.bin or gtk.window. How can I test whether gtk.container is somewhere up in the constructor chain?

    Read the article

  • Init var without copy constructor

    - by Ockonal
    Hello, I have some class(Window) without copy constructor (it's private). I can't understand how to init var of this class in my own class: class MyClass { Window obj; // Hasn't copy constructor public: void init() { obj = Window(/* constructor params */); // [error] obj(/* constructor params */); // [error] } } Error 1: initializing argument 1 of ‘Window::Window(WindowHandle, const sf::WindowSettings&)’ Error 2: ‘NonCopyable& NonCopyable::operator=(const NonCopyable&)’ is private But it works in this way: Window obj(/* constructor params */);

    Read the article

  • Doubt about constructor in JAVA

    - by Harry Joy
    I have few doubts regarding constructor in java Can a constructor be private? If yes then in which condition? Constructor is a method or not? If constructor does not return anything then why we are getting a new Object every time we call it. Whats the default access modifier of a constructor if we did not specify. Thanks & Regards Edit---------- Answer for 1 & 3 are very clear. But still doubt about 2&4 as i'm getting different answers for them.

    Read the article

  • C++ Array Initialization in Function Call or Constructor Call

    - by david
    This question is related to the post here. Is it possible to initialize an array in a function call or constructor call? For example, class foo's constructor wants an array of size 3, so I want to call foo( { 0, 0, 0 } ). I've tried this, and it does not work. I'd like to be able to initialize objects of type foo in other objects' constructor initialization lists, or initialize foo's without first creating a separate array. Is this possible?

    Read the article

  • Java constructor with large arguments or Java bean getter/setter approach

    - by deelo55
    Hi, I can't decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor at least you enforce that all the fields are set. Java Beans easier to see which variables are being set instead of a huge list. The builder pattern DOES NOT seem suitable here as all the fields are mandatory and the builder requires you put all mandatory parameters in the builder constructor. Thanks, D

    Read the article

  • Accessing constructor from abstract base class with reflection

    - by craesh
    Hi! I'm playing around with Java's Reflection. I have an abstract class Base with a constructor. abstract class Base { public Base( String foo ) { // do some magic } } I have some further classes extending Base. They don't contain much logic. I want to instantiate them with Base's constructor, without having to write some proxy contructors in those derived classes. And of course, I want to instantiate those derived classes with Reflection. Say: Class cls = SomeDerivedClass.class; Constructor constr; constr = cls.getConstructor( new Class[] { String.class } ); // will return null Class clsBase = Base.class; constr = clsBase.getConstructor( new Class[] { String.class } ); // ok Base obj = (Base) constr.newInstance( new Object[] { "foo" } ); // will throw InstantiationException because it belongs to an abstract class Any ideas, how I can instantiate a derived class with Base's constructor? Or must I declare those dumb proxy constructors?

    Read the article

  • Can a single argument constructor with a default value be subject to implicit type conversion

    - by Richard
    I understand the use of the explicit keyword to avoid the implicit type conversions that can occur with a single argument constructor, or with a constructor that has multiple arguments of which only the first does not have a default value. However, I was wondering, does a single argument constructor with a default value behave the same as one without a default value when it comes to implicit conversions?

    Read the article

  • Good style for handling constructor failure of critical object

    - by mtlphil
    I'm trying to decide between two ways of instantiating an object & handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue. I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor and close it in the destructor. It will throw an exception inherited from std::exception in the constructor if the MIDI device cannot be opened. Which of the following ways of catching constructor exceptions for this object would be more in line with C++ best practices Method 1 - Stack allocated object, only in scope inside try block #include <iostream> #include "simplemidiout.h" int main() { try { SimpleMIDIOut myOut; //constructor will throw if MIDI device cannot be opened myOut.PlayNote(60,100); //..... //myOut goes out of scope outside this block //so basically the whole program has to be inside //this block. //On the plus side, it's on the stack so //destructor that handles object cleanup //is called automatically, more inline with RAII idiom? } catch(const std::exception& e) { std::cout << e.what() << std::endl; std::cin.ignore(); return 1; } std::cin.ignore(); return 0; } Method 2 - Pointer to object, heap allocated, nicer structured code? #include <iostream> #include "simplemidiout.h" int main() { SimpleMIDIOut *myOut; try { myOut = new SimpleMIDIOut(); } catch(const std::exception& e) { std::cout << e.what() << std::endl; delete myOut; return 1; } myOut->PlayNote(60,100); std::cin.ignore(); delete myOut; return 0; } I like the look of the code in Method 2 better, don't have to jam my whole program into a try block, but Method 1 creates the object on the stack so C++ manages the object's life time, which is more in tune with RAII philosophy isn't it? I'm still a novice at this so any feedback on the above is much appreciated. If there's an even better way to check for/handle constructor failure in a siatuation like this please let me know.

    Read the article

  • Getting the instance when Constructor#newInstance throws?

    - by Shtééf
    I'm working on a simple plugin system, where third party plugins implement a Plugin interface. A directory of JARs is scanned, and the implementing classes are instantiated with Constructor#newInstance. The thing is, these plugins call back into register* methods of the plugin host. These registrations use the Plugin instance as a handle. My problem is how to clean up these registrations if the constructor decides to fail and throw halfway through. InvocationTargetException doesn't seem to have anything on it to get the instance. Is there a way to get at the instance of an exception throwing constructor? P.S.: It's typically strongly advised to users that the constructor not do anything, but in practice people are doing it any ways.

    Read the article

  • Issue calling superclass method in subclass constructor

    - by stormin986
    I get a NullPointerException calling a Superclass Method in Subclass Inner Class Constructor... What's the Deal? In my application's main class (subclass of Application), I have a public inner class that simply contains 3 public string objects. In the parent class I declare an object of that inner class. public class MainApplication extends Application { public class Data { public String x; public String y; public String z; } private Data data; MainApplication() { data = new Data() data.x = SuperClassMethod(); } } After I instantiate the object in the constructor, I get a runtime error when I try to assign a value in the inner class with a superclass method. Any idea what's up here?? Can you not call superclass methods in the subclass constructor? ** Edit ** Original question was about inner class member assignment in outer class constructor. Turned out the issue was with calling a superclass method in the class's constructor. It was giving me a null pointer exception. Thus, the question has changed.

    Read the article

  • C++ superclass constructor calling rules

    - by levik
    What are the C++ rules for calling the superclass constructor from a subclass one?? For example I know in Java, you must do it as the first line of the subclass constructor (and if you don't an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).

    Read the article

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