Search Results

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

Page 9/187 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • How is the C++ synthesized move constructor affected by volatile and virtual members?

    - by user1827766
    Look at the following code: struct node { node(); //node(const node&); //#1 //node(node&&); //#2 virtual //#3 ~node (); node* volatile //#4 next; }; main() { node m(node()); //#5 node n=node(); //#6 } When compiled with gcc-4.6.1 it produces the following error: g++ -g --std=c++0x -c -o node.o node.cc node.cc: In constructor node::node(node&&): node.cc:3:8: error: expression node::next has side-effects node.cc: In function int main(): node.cc:18:14: note: synthesized method node::node(node&&) first required here As I understand the compiler fails to create default move or copy constructor on line #6, if I uncomment either line #1 or #2 it compiles fine, that is clear. The code compiles fine without c++0x option, so the error is related to default move constructor. However, what in the node class prevents default move constructor to be created? If I comment any of the lines #3 or #4 (i.e. make the destructor non-virtual or make data member non-volatile) it compiles again, so is it the combination of these two makes it not to compile? Another puzzle, line #5 does not cause an compilation error, what is different from line #6? Is it all specific for gcc? or gcc-4.6.1?

    Read the article

  • Why isn't the static constructor of the parent class called when invoking a method on a nested class

    - by Ryan Ische
    Given the following code, why isn't the static constructor of "Outer" called after the first line of "Main"? namespace StaticTester { class Program { static void Main( string[] args ) { Outer.Inner.Go(); Console.WriteLine(); Outer.Go(); Console.ReadLine(); } } public static partial class Outer { static Outer() { Console.Write( "In Outer's static constructor\n" ); } public static void Go() { Console.Write( "Outer Go\n" ); } public static class Inner { static Inner() { Console.Write( "In Inner's static constructor\n" ); } public static void Go() { Console.Write( "Inner Go\n" ); } } } }

    Read the article

  • What is the difference between a constructor and a procedure in Delphi records?

    - by HMcG
    Is there difference in behavior between a constructor call and a procedure call in Delphi records? I have a D2010 code sample I want to convert to D2009 (which I am using). The sample uses a parameterless constructor, which is not permitted in Delphi 2009. If I substitute a simple parameterless procedure call, is there any functional difference for records? I.E. TVector = record private FImpl: IVector; public constructor Create; // not allowed in D2009 end; becomes TVector = record private FImpl: IVector; public procedure Create; // so change to procedure end; As far as I can see this should work, but I may be missing something.

    Read the article

  • How are Flash library symbols constructed? Why are width/height already available in constructor?

    - by Triynko
    Suppose I draw a square on the stage, convert it to a symbol, export it for ActionScript with a classname of "MySquare" (and of course a base class of MovieClip). How is it that in the MySquare constructor, the width and height of this MovieClip are already available? In fact, any named instances in the clip are also available. I'm confused about how the Flash player seems to be able to pre-construct my movie clip by populating its properties and child clips before my constructor for the class ever runs. I thought that it would have to first construct the clip, calling my constructor code, and then construct and add any children, but obviously the player is doing something special for clips designed in the Flash authoring environment.

    Read the article

  • Configuring Unity with a closed generic constructor parmater

    - by fearofawhackplanet
    I've been trying to read the article here but I still can't understand it. I have a constructor resembling the following: IOrderStore orders = new OrderStore(new Repository<Order>(new OrdersDataContext())); The constructor for OrderStore: public OrderStore(IRepository<Order> orderRepository) Constructor for Repository<T>: public Repository(DataContext dataContext) How do I set this up in the Unity config file? UPDATE: I've spent the last few hours banging my head against this, and although I'm not really any closer to getting it right I think at least I can be a little more specific about the problem. I've got my IRespository<T> working ok: <typeAlias alias="IRepository" type="MyAssembly.IRepository`1, MyAssembly" /> <typeAlias alias="Repository" type="MyAssembly.Repository`1, MyAssembly" /> <typeAlias alias="OrdersDataContext" type="MyAssembly.OrdersDataContext, MyAssembly" /> <types> <type type="OrdersDataContext"> <typeConfig> <constructor /> <!-- ensures paramaterless constructor used --> </typeConfig> </type> <type type="IRepository" mapTo="Repository"> <typeConfig> <constructor> <param name="dataContext" parameterType="OrdersDataContext"> <dependency /> </param> </constructor> </typeConfig> </type> </types> So now I can get an IRepository like so: IRepository rep = _container.Resolve(); and that all works fine. The problem now is when trying to add the configuration for IOrderStore <type type="IOrderStore" mapTo="OrderStore"> <typeConfig> <constructor> <param name="ordersRepository" parameterType="IRepository"> <dependency /> </param> </constructor> </typeConfig> </type> When I add this, Unity blows up when trying to load the config file. The error message is OrderStore does not have a constructor that takes the parameters (IRepository`1). What I think this is complaining about is because the OrderStore constructor takes a closed IRepository generic type, ie OrderStore(IRepository<Order>) and not OrderStore(IRepository<T>) I don't have any idea how to resolve this.

    Read the article

  • Explicit constructor still has default values even though a default constructor is not invoked.

    - by Phoenix
    According to my understanding a default constructor initializes the state of the object to default values, so if i provide an explicit no-arg public constructor like this then how are the values of d and e still getting initialized to zero because in this case the default constructor is not invoked. public class B extends A{ private int d; private int e; public B() { System.out.println(d); System.out.println(e); } } EDIT:: The only thing default constructor does is call to super() then how come if i have a explicitly mentioned a constructor here and A has a protected variable say c which is initialized to 17 in its constructor. Should I not be explicitly calling super() to be able to see that change since I'm using my own constructor ? Why is B still getting the value of 17 through inheritance ?

    Read the article

  • Calling child constructor by casting (ChildClass)parentObject; to track revisions

    - by FreshCode
    To track revisions of a Page class, I have a PageRevision class which inherits from Page and adds a revision ID (Guid RevisionID;). If possible, how should I cast an existing Page object to a PageRevision and ensure that the PageRevision constructor is called to create a new revision ID? I could could have a PageRevision(Page page) constructor which generates the Guid and copies all the Page attributes, but I want to automate it, especially if a Page class has many attributes (and I later add one, and forget to modify the copy constructor). Desired use Page page = new Page(123, "Page Title", "Page Body"); // where 123 is page ID PageRevision revision = (PageRevision)page; // now revision.RevisionID should be a new Guid. Page, PageRevision classes: public class Page { public int ID { get; set; } public string Title { get; set; } public string Body { get; set; } } public class PageRevision : Page { public Guid RevisionID { get; set; } public PageRevision() { this.RevisionID = Guid.NewGuid(); } }

    Read the article

  • Constructor parameter validation in C# - Best practices

    - by MPelletier
    What is the best practice for constructor parameter validation? Suppose a simple bit of C#: public class MyClass { public MyClass(string text) { if (String.IsNullOrEmpty(text)) throw new ArgumentException("Text cannot be empty"); // continue with normal construction } } Would it be acceptable to throw an exception? The alternative I encountered was pre-validation, before instantiating: public class CallingClass { public MyClass MakeMyClass(string text) { if (String.IsNullOrEmpty(text)) { MessageBox.Show("Text cannot be empty"); return null; } else { return new MyClass(text); } } }

    Read the article

  • Using new to allocate an array of class elements with an overloaded constructor in C++.

    - by GordoN
    As an example say I have a class foo that does not have a default constructor but one that looks like this foo:foo(int _varA,int _varB) { m_VarA = _varA; m_VarB = _varB; } How would I allocate an array of these. I seem to remember trying somthing like this unsuccessfully. foo* MyArray = new foo[100](25,14). I don't think this will work either. foo* MyArray = new foo[100](25,14) Can this be done? I typically do this by writing the default constructor using some preset values for _varA and _varB. Then adding a function to reset _varA and _varB for each element but that will not work for this case. Thanks for the help.

    Read the article

  • Performing user authentication in a CodeIgniter controller constructor?

    - by msanford
    In "The Clean Code Talks -- Unit Testing" (http://youtu.be/wEhu57pih5w), Miško Hevery mentions that "as little work as possible should be done in constructors [to make classes more easily testable]'. It got me thinking about the way I have implemented my user authentication mechanism. Having delved into MVC development through CodeIgniter, I designed my first web application to perform user authentication for protected resources in controllers' constructors in cases where every public function in that controller requires the user to be authenticated. For controllers with public methods having mixed authentication requirements, I would naturally move the authentication from the constructor to each method requiring authentication (though I don't currently have a need for this). I made this choice primarily to keep the controller tight, and to ensure that all resources in the controller are always covered. As for code longevity and maintainability: given the application structure, I can't foresee a situation in which one of the affected controllers would need a public method that didn't require user authentication, but I can see this as a potential drawback in general with this implementation (i.e., requiring future refactoring). Is this a good idea?

    Read the article

  • constructor should not call methods

    - by Stefano Borini
    I described to a colleague why a constructor calling a method is an antipattern. example (in my rusty C++) class C { public : C(int foo); void setFoo(int foo); private: int foo; } C::C(int foo) { setFoo(foo); } void C::setFoo(int foo) { this->foo = foo } I would like to motivate better this fact through your additional contribute. If you have examples, book references, blog pages, or names of principles, they would be very welcome. Edit: I'm talking in general, but we are coding in python.

    Read the article

  • Constructor should generally not call methods

    - by Stefano Borini
    I described to a colleague why a constructor calling a method can be an antipattern. example (in my rusty C++) class C { public : C(int foo); void setFoo(int foo); private: int foo; } C::C(int foo) { setFoo(foo); } void C::setFoo(int foo) { this->foo = foo } I would like to motivate better this fact through your additional contribute. If you have examples, book references, blog pages, or names of principles, they would be very welcome. Edit: I'm talking in general, but we are coding in python.

    Read the article

  • Implicit and Explicit implementation of interface.

    - by Amby
    While working on a upgrade i happened to come across a code like this. interface ICustomization { IMMColumnsDefinition GetColumnsDefinition(); } class Customization : ICustomization { private readonly ColumnDefinition _columnDefinition; //More code here. public ColumnsDefinition GetColumnsDefinition() { return _columnDefinition; } ColumnsDefinition ICustomization.GetColumnsDefinition() //redundant { return GetColumnsDefinition(); } } My question is: Is there any need/use of 'explicit' implementation of interface in this piece of code? Will it create any problem if i remove the method (explicit implementation of interface) that i have marked "redundant" above? PS: I understand that explicit implementation of interface is very important, and it can be used when we need to give access to a method at interface level only, and to use two interface with same signature of method.

    Read the article

  • what's an option strict and explicit?

    - by Ygam
    I saw this post: "Typos… Just use option strict and explicit please.. during one software development project, which I was on as a consultant, they were getting ridiculous amounts of errors everywhere… turned out the developer couldn’t spell and would declare variables with incorrect spelling.. no big deal, until you use the correct spelling when you’re assigning a value to it… and you had option explicit off. Ouch to them…" what is an option strict and explicit anyway? I have googled it up but can't get the idea (because mostly it's Visual Basic, I'm doing PHP)

    Read the article

  • Is c++ explicit conversion really that bad?

    - by LoudNPossiblyRight
    My knowledge in c++ at this point is more academic than anything else and in all my reading thus far, the use of explicit conversion with named casts (const_cast, static_cast, reinterpret_cast, dynamic_cast) has come with a big warning label (and it's easy to see why) that pretty much implies explicit conversion is symptomatic of bad design and should only be used as a last resort in desperate circumstances. So i have to ask: Is explicit conversion with named casts really just jury rigging code or is there a more graceful and positive application to this feature? Is there a good example of the latter? Thanks in advance.

    Read the article

  • Is std::move really needed on initialization list of constructor for heavy members passed by value?

    - by PiotrNycz
    Recently I read an example from cppreference.../vector/emplace_back: struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "I am being constructed.\n"; } My question: is this std::move really needed? My point is that compiler sees that this p_name is not used in the body of constructor, so, maybe, there is some rule to use move semantics for it by default? That would be really annoying to add std::move on initialization list to every heavy member (like std::string, std::vector). Imagine hundreds of KLOC project written in C++03 - shall we add everywhere this std::move? This question: move-constructor-and-initialization-list answer says: As a golden rule, whenever you take something by rvalue reference, you need to use it inside std::move, and whenever you take something by universal reference (i.e. deduced templated type with &&), you need to use it inside std::forward But I am not sure: passing by value is rather not universal reference?

    Read the article

  • Constructor vs setter validations

    - by Jimmy
    I have the following class : public class Project { private int id; private String name; public Project(int id, String name, Date creationDate, int fps, List<String> frames) { if(name == null ){ throw new NullPointerException("Name can't be null"); } if(id == 0 ){ throw new IllegalArgumentException("id can't be zero"); } this.name = name; this.id = id; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } I have three questions: Do I use the class setters instead of setting the fields directly. One of the reason that I set it directly, is that in the code the setters are not final and they could be overridden. If the right way is to set it directly and I want to make sure that the name filed is not null always. Should I provide two checks, one in the constructor and one in the setter. I read in effective java that I should use NullPointerException for null parameters. Should I use IllegalArgumentException for other checks, like id in the example.

    Read the article

  • Initializing entities vs having a constructor parameter

    - by Vee
    I'm working on a turn-based tile-based puzzle game, and to create new entities, I use this code: Field.CreateEntity(10, 5, Factory.Player()); This creates a new Player at [10; 5]. I'm using a factory-like class to create entities via composition. This is what the CreateEntity method looks like: public void CreateEntity(int mX, int mY, Entity mEntity) { mEntity.Field = this; TileManager.AddEntity(mEntity, true); GetTile(mX, mY).AddEntity(mEntity); mEntity.Initialize(); InvokeOnEntityCreated(mEntity); } Since many of the components (and also logic) of the entities require to know what the tile they're in is, or what the field they belong to is, I need to have mEntity.Initialize(); to know when the entity knows its own field and tile. The Initialize(); method contains a call to an event handler, so that I can do stuff like this in the factory class: result.OnInitialize += () => result.AddTags(TDLibConstants.GroundWalkableTag, TDLibConstants.TrapdoorTag); result.OnInitialize += () => result.AddComponents(new RenderComponent(), new ElementComponent(), new DirectionComponent()); This works so far, but it is not elegant and it's very open to bugs. I'm also using the same idea with components: they have a parameterless constructor, and when you call the AddComponent(mComponent); method in an entity, it is the entity's job to set the component's entity to itself. The alternative would be having a Field, int, int parameters in the factory class, to do stuff like: new Entity(Field, 10, 5); But I also don't like the fact that I have to create new entities like this. I would prefer creating entities via the Field object itself. How can I make entity/component creation more elegant and less prone to bugs?

    Read the article

  • Use constructor or setter method?

    - by user633600
    I am working on a UI code where I have an Action class, something like this - public class MyAction extends Action { public MyAction() { setText("My Action Text"); setToolTip("My Action Tool tip"); setImage("Some Image"); } } When this Action class was created it was pretty much assumed that the Action class wont be customizable (in a sense- its text, tooltip or image will be not be changed anywhere in the code). Of late, now we are in need of changing the action text at some location in code. So I suggested my co-worker to remove the hardcoded action text from the constructor and accept it as an argument, so that everybody is forced to pass the action text. Something like this code below - public class MyAction extends Action { public MyAction(String actionText) { setText(actionText); setTooltip("My Action tool tip); setImage("My Image"); } } He however thinks that since setText() method belongs to base class. It can be flexibly used to pass the action text wherever action instance is created. That way, there is no need to change the existing MyAction class. So his code would look something like this. MyAction action = new MyAction(); //this creates action instance with the hardcoded text action.setText("User required new action text"); //overwrite the exisitng text. I am not sure if that is a correct way to deal with problem. I think in above mentioned case user is anyway going to change the text, so why not force him while constructing the action. The only benefit I see with the original code is that user can create Action class without much thinking about setting text.

    Read the article

  • WCF Runtime Error while using Constructor

    - by Pranesh Nair
    Hi all, I am new to WCF i am using constructor in my WCF service.svc.cs file....It throws this error when i use the constructor The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host. When i remove the constructor its working fine....But its compulsory that i have to use constructor... This is my code namespace UserAuthentication { [ServiceBehavior(InstanceContextMode=System.ServiceModel.InstanceContextMode.Single)] public class UserAuthentication : UserRepository,IUserAuthentication { private ISqlMapper _mapper; private IRoleRepository _roleRepository; public UserAuthentication(ISqlMapper mapper): base(mapper) { _mapper = mapper; _roleRepository = new RoleRepository(_mapper); } public string EduvisionLogin(EduvisionUser aUser, int SchoolID) { UserRepository sampleCode= new UserRepository(_mapper); sampleCode.Login(aUser); return "Login Success"; } } } can anyone provide ideas or suggestions or sample code hw to resolve this issue...

    Read the article

  • Generic Abstract Singleton with Custom Constructor in C#

    - by Heka
    I want to write a generic singleton with an external constructor. In other words the constructor can be modified. I have 2 designs in my mind but I don't know whether they are practical or not. First one is to enforce derived class' constructor to be non-public but I do not know if there is a way of it? Second one is to use a delegate and call it inside the constructor? It isn't necessarily to be a constructor. The reason I chose custom constructor is doing some custom initializations. Any suggestions would be appreciated :)

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >