cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : General C++ Programming : Arrays in Constructors
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Articles
Lounge
Jobs

-

post  Arrays in Constructors

theChameleon (9)
Hello, i'd like to write something that fixes the size of an array inside a constructor, instead of fixing the size when declaring the array.

how do i do that?

i have tried...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class aClass{
        int size;
        int arr[];
    public:
        aClass();
};

aClass::aClass(){
    size = 10;
    arr[size];
    for(int i = 0; i < size; i++){
        arr[i] = 0; //initialise
    }

}


something like that, but, after running the main prog, a window will pop up telling me that theres an unhandled runtime exception.

is there a way to do wat i did, but get rid of this runtime exception thingie? thanks.

do i have to catch/throw some exception, and if so, what exception and how? im pretty new to this lang, so any help would be much appreciated.
| Last edited on
Grey Wolf (637)
You could do somthing like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

class aClass{
        int size;
        int *arr;
    public:
        aClass();
        ~aClass();
};

aClass::aClass()
{
    size = 10;
    arr = new int[size];
    for(int i = 0; i < size; i++)
    {
        arr[i] = 0; //initialise
    }
}

aClass::~aClass()
{
   delete[] arr;    
}

int main() 
{
    aClass test;
}


But you would be better off using a vector
| Last edited on
Zaita (1151)
"do i have to catch/throw some exception, and if so, what exception and how? im pretty new to this lang, so any help would be much appreciated."

1
2
3
4
5
try {

} catch (exception &ex) {
 cout << ex.what() << endl;
}
|
theChameleon (9)
thanks Grey Wolf, for your prompt reply. that really helped in getting rid of that exception thingie.

a vector is not required, in my case, coz the number is fixed and not dynamic, but thanks anyway.
|

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2008 - All rights reserved - v2.2
Spotted an error? contact us