Search Results

Search found 4652 results on 187 pages for 'explicit constructor'.

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

  • Purpose of Explicit Default Constructors

    - by Dennis Zickefoose
    I recently noticed a class in C++0x that calls for an explicit default constructor. However, I'm failing to come up with a scenario in which a default constructor can be called implicitly. It seems like a rather pointless specifier. I thought maybe it would disallow Class c; in favor of Class c = Class(); but that does not appear to be the case. Some relevant quotes from the C++0x FCD, since it is easier for me to navigate [similar text exists in C++03, if not in the same places] 12.3.1.3 [class.conv.ctor] A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value initialization (8.5). It goes on to provide an example of an explicit default constructor, but it simply mimics the example I provided above. 8.5.6 [decl.init] To default-initialize an object of type T means: — if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); 8.5.7 [decl.init] To value-initialize an object of type T means: — if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor); In both cases, the standard calls for the default constructor to be called. But that is what would happen if the default constructor were non-explicit. For completeness sake: 8.5.11 [decl.init] If no initializer is specified for an object, the object is default-initialized; From what I can tell, this just leaves conversion from no data. Which doesn't make sense. The best I can come up with would be the following: void function(Class c); int main() { function(); //implicitly convert from no parameter to a single parameter } But obviously that isn't the way C++ handles default arguments. What else is there that would make explicit Class(); behave differently from Class();? The specific example that generated this question was std::function [20.8.14.2 func.wrap.func]. It requires several converting constructors, none of which are marked explicit, but the default constructor is.

    Read the article

  • 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

  • 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

  • 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

  • Explicit C# interface implementation of interfaces that inherit from other interfaces

    - by anthony
    Consider the following three interfaces: interface IBaseInterface { event EventHandler SomeEvent; } interface IInterface1 : IBaseInterface { ... } interface IInterface 2 : IBaseInterface { ... } Now consider the following class that implements both IInterface1 and IInterface 2: class Foo : IInterface1, IInterface2 { event EventHandler IInterface1.SomeEvent { add { ... } remove { ... } } event EventHandler IInterface2.SomeEvent { add { ... } remove { ... } } } This results in an error because SomeEvent is not part of IInterface1 or IInterface2, it is part of IBaseInterface. How can the class Foo implement both IInterface1 and IInterface2?

    Read the article

  • Lazy Loading,Eager Loading,Explicit Loading in Entity Framework 4

    - by nikolaosk
    This is going to be the ninth post of a series of posts regarding ASP.Net and the Entity Framework and how we can use Entity Framework to access our datastore. You can find the first one here , the second one here , the third one here , the fourth one here , the fifth one here ,the sixth one here ,the seventh one here and the eighth one here . I have a post regarding ASP.Net and EntityDataSource . You can read it here .I have 3 more posts on Profiling Entity Framework applications. You can have a...(read more)

    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

  • ASP.NET MVC 3: Implicit and Explicit code nuggets with Razor

    - by ScottGu
    This is another in a series of posts I’m doing that cover some of the new ASP.NET MVC 3 features: New @model keyword in Razor (Oct 19th) Layouts with Razor (Oct 22nd) Server-Side Comments with Razor (Nov 12th) Razor’s @: and <text> syntax (Dec 15th) Implicit and Explicit code nuggets with Razor (today) In today’s post I’m going to discuss how Razor enables you to both implicitly and explicitly define code nuggets within your view templates, and walkthrough some code examples of each of them.  Fluid Coding with Razor ASP.NET MVC 3 ships with a new view-engine option called “Razor” (in addition to the existing .aspx view engine).  You can learn more about Razor, why we are introducing it, and the syntax it supports from my Introducing Razor blog post. Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote the start and end of server blocks within your HTML. The Razor parser is smart enough to infer this from your code. This enables a compact and expressive syntax which is clean, fast and fun to type. For example, the Razor snippet below can be used to iterate a collection of products and output a <ul> list of product names that link to their corresponding product pages: When run, the above code generates output like below: Notice above how we were able to embed two code nuggets within the content of the foreach loop.  One of them outputs the name of the Product, and the other embeds the ProductID within a hyperlink.  Notice that we didn’t have to explicitly wrap these code-nuggets - Razor was instead smart enough to implicitly identify where the code began and ended in both of these situations.  How Razor Enables Implicit Code Nuggets Razor does not define its own language.  Instead, the code you write within Razor code nuggets is standard C# or VB.  This allows you to re-use your existing language skills, and avoid having to learn a customized language grammar. The Razor parser has smarts built into it so that whenever possible you do not need to explicitly mark the end of C#/VB code nuggets you write.  This makes coding more fluid and productive, and enables a nice, clean, concise template syntax.  Below are a few scenarios that Razor supports where you can avoid having to explicitly mark the beginning/end of a code nugget, and instead have Razor implicitly identify the code nugget scope for you: Property Access Razor allows you to output a variable value, or a sub-property on a variable that is referenced via “dot” notation: You can also use “dot” notation to access sub-properties multiple levels deep: Array/Collection Indexing: Razor allows you to index into collections or arrays: Calling Methods: Razor also allows you to invoke methods: Notice how for all of the scenarios above how we did not have to explicitly end the code nugget.  Razor was able to implicitly identify the end of the code block for us. Razor’s Parsing Algorithm for Code Nuggets The below algorithm captures the core parsing logic we use to support “@” expressions within Razor, and to enable the implicit code nugget scenarios above: Parse an identifier - As soon as we see a character that isn't valid in a C# or VB identifier, we stop and move to step 2 Check for brackets - If we see "(" or "[", go to step 2.1., otherwise, go to step 3  Parse until the matching ")" or "]" (we track nested "()" and "[]" pairs and ignore "()[]" we see in strings or comments) Go back to step 2 Check for a "." - If we see one, go to step 3.1, otherwise, DO NOT ACCEPT THE "." as code, and go to step 4 If the character AFTER the "." is a valid identifier, accept the "." and go back to step 1, otherwise, go to step 4 Done! Differentiating between code and content Step 3.1 is a particularly interesting part of the above algorithm, and enables Razor to differentiate between scenarios where an identifier is being used as part of the code statement, and when it should instead be treated as static content: Notice how in the snippet above we have ? and ! characters at the end of our code nuggets.  These are both legal C# identifiers – but Razor is able to implicitly identify that they should be treated as static string content as opposed to being part of the code expression because there is whitespace after them.  This is pretty cool and saves us keystrokes. Explicit Code Nuggets in Razor Razor is smart enough to implicitly identify a lot of code nugget scenarios.  But there are still times when you want/need to be more explicit in how you scope the code nugget expression.  The @(expression) syntax allows you to do this: You can write any C#/VB code statement you want within the @() syntax.  Razor will treat the wrapping () characters as the explicit scope of the code nugget statement.  Below are a few scenarios where we could use the explicit code nugget feature: Perform Arithmetic Calculation/Modification: You can perform arithmetic calculations within an explicit code nugget: Appending Text to a Code Expression Result: You can use the explicit expression syntax to append static text at the end of a code nugget without having to worry about it being incorrectly parsed as code: Above we have embedded a code nugget within an <img> element’s src attribute.  It allows us to link to images with URLs like “/Images/Beverages.jpg”.  Without the explicit parenthesis, Razor would have looked for a “.jpg” property on the CategoryName (and raised an error).  By being explicit we can clearly denote where the code ends and the text begins. Using Generics and Lambdas Explicit expressions also allow us to use generic types and generic methods within code expressions – and enable us to avoid the <> characters in generics from being ambiguous with tag elements. One More Thing….Intellisense within Attributes We have used code nuggets within HTML attributes in several of the examples above.  One nice feature supported by the Razor code editor within Visual Studio is the ability to still get VB/C# intellisense when doing this. Below is an example of C# code intellisense when using an implicit code nugget within an <a> href=”” attribute: Below is an example of C# code intellisense when using an explicit code nugget embedded in the middle of a <img> src=”” attribute: Notice how we are getting full code intellisense for both scenarios – despite the fact that the code expression is embedded within an HTML attribute (something the existing .aspx code editor doesn’t support).  This makes writing code even easier, and ensures that you can take advantage of intellisense everywhere. Summary Razor enables a clean and concise templating syntax that enables a very fluid coding workflow.  Razor’s ability to implicitly scope code nuggets reduces the amount of typing you need to perform, and leaves you with really clean code. When necessary, you can also explicitly scope code expressions using a @(expression) syntax to provide greater clarity around your intent, as well as to disambiguate code statements from static markup. Hope this helps, Scott P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

    Read the article

  • Why can't I use interface with explicit operator?

    - by theburningmonk
    Hi, I'm just wondering if anyone knows the reason why you are not allowed to use interfaces with the implicit or explicit operators? E.g. this raises compile time error: public static explicit operator MyPlayer(IPlayer player) { ... } "user-defined conversions to or from an interface are not allowed" Thanks,

    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

  • Object initializer with explicit interface in C#

    - by Ben Aston
    How can I use an object initializer with an explicit interface implementation in C#? public interface IType { string Property1 { get; set; } } public class Type1 : IType { string IType.Property1() { get; set; } } ... //doesn't work var v = new Type1 { IType.Property1 = "myString" };

    Read the article

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