CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2001
    Posts
    2,529

    wierd allocation

    I am wondering about this piece of code:

    Code:
        class Deck
        {
            //Wow didn't know you would ever want to allocate in the class definition
            private List<Card> Cards = new List<Card>(52);//52 is not a hard and fast number
            public Deck()
            {
    It looks like the List will be a static because it gets allocated when the class is read by the compiler. Is this sort of a bad way to allocate this? Shouldn't the objects be allocated in the constructor?
    ahoodin
    To keep the plot moving, that's why.

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: wierd allocation

    No, it is not static at all, it is by definition an instance variable, i.e., each instance of a class owns a separate copy. You are confused about when it is allocated, and it is not bad at all; you should do that when you need a variable to hang around for the lifetime of an object. What do you think is going on when you create a backing field for a property? You are creating an instance variable and two methods, one to set it and one to return it.

  3. #3
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: wierd allocation

    Just to add to BigEd781's explanation...

    Instance fields will be initialised when the instance of the class is created. You could decided to have initialisation in the constructor (directly or via an initialisation method). The benefit of that is when you have a complex initialisation (e.g. you are initialising a collection of items) or when you have constructor arguments that are key for the initialisation of the class. Secondly the number 52 only specifies the initial capacity of the list. The list can grow if need be.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured