Array Declaration in class
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Array Declaration in class

  1. #1
    Join Date
    Apr 2009
    Posts
    1

    Array Declaration in class

    hey guys,

    I want to create a class that has an array of unsigned integers whereby the constructor takes in a single unsigned integer to be the size of the array, i.e.

    So for I have, in myclass.h

    class myclass
    {
    private:
    unsigned int grades[]; //(i)
    public:
    myclass(unsigned int Size)
    };

    In myclass.cpp
    #include "myclass.h"

    myclass:myclass(unsigned int Size)
    {
    grades = unsigned int[Size]; //(ii)
    }

    int main(void)
    {
    myclass Test(10);
    return 0;
    }

    When I build this (In Visual Studio 2005 .NET), I can the following error messages,
    in reference to (i)
    warning C4200: nonstandard extension used : zero-sized array in struct/union
    in reference to (ii)
    error C2062: type 'unsigned int' unexpected

    Where am I going wrong??

    Thanks in Advance,

    David

  2. #2
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: Array Declaration in class

    Code:
    unsigned int grades[];
    Your array has no size.

    Code:
    unsigned int grades[10];
    now it has. But what you are trying should look like this:

    Code:
    unsigned int *grades;
    grades = new int[10];
    ...
    
    delete []grades.

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,891

    Re: Array Declaration in class

    If you write it that way, you'll have to define the destructor, copy constructor, and operator= as well in order to ensure the class objects don't become corrupted. (Alternatively you can simply define the destructor and disable the other two by declaring them private.)

    If you want to save all that effort, declare grades as a std::vector<unsigned int>. Then the default-generated versions of each of those functions will be good enough.

  4. #4
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    Re: Array Declaration in class

    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center