473,799 Members | 3,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can a class has a member array which will be dynamically allocated during runtime?

4 New Member
Can a class has a member array which will be dynamically allocated during runtime? Such as

double* A=new double[n]

here n is an integer member variable and will be determined during runtime and the class will have the array *A allocated.

Thanks in advance.
Aug 21 '08 #1
7 1785
Banfa
9,065 Recognized Expert Moderator Expert
Yes

You might normally allocate the memory for the array in the constructor or some other member function of the class and then delete it in the destructor.
Aug 21 '08 #2
runn
4 New Member
The code is below:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class MyClass
  5. {
  6.       public:
  7.       int n;
  8.       double* A;  // One of the problem is the declaration I think ...
  9.       MyClass(int);
  10.       virtual ~MyClass();
  11.       void Print();
  12. };
  13.  
  14.  
  15. MyClass::MyClass(int _n)     
  16. {
  17.      n=_n;
  18.      double* A=new double[n];
  19.      if (!A) abort();
  20.      A[0]=0.0;A[1]=10.0;A[2]=20.0;A[3]=30.0;
  21.      cout <<A[0]<<endl;
  22.      cout <<A[1]<<endl;
  23.      cout <<A[2]<<endl;
  24.      cout <<A[3]<<endl;
  25.      cout <<""<<endl;
  26. }
  27.  
  28. MyClass::~MyClass()     
  29. {
  30.      delete []A;
  31. }
  32.  
  33. void MyClass::Print()
  34. {
  35.      cout <<A[0]<<endl;
  36.      cout <<A[1]<<endl;
  37.      cout <<A[2]<<endl;
  38.      cout <<A[3]<<endl;
  39. }
  40.  
  41.  
  42. int main ()
  43. {
  44.  MyClass m(4);
  45.  m.Print();
  46.  return 0;
  47. }
and the output of this code is:
  • 0
    10
    20
    30

    1.98218e-317
    1.17289e-046
    0
    1.94765e-308


First 4 output comes from the constructor. Considering the last 4 output, I understand that allocated memory is local to the constructor member function.

Another problem is the declaration of A I think...
Aug 21 '08 #3
Banfa
9,065 Recognized Expert Moderator Expert
That is because in the constructor rather than using the member variable A you declare a local variable A on the stack that is then lost when the function exits producing a memory leak.

Nothing is ever assigned to the member variable A.
Aug 21 '08 #4
runn
4 New Member
If I use the A in the member function in which the memory is allocated there is no problem. Every thing is OK. However I want to use it outside the member function also. For this purpose, When I make an declaration as

double* A[n]

compiler says:
invalid use of non-static data member `MyClass::n'

If I make n is static, there will be only one n while there are several MyClass objects. Each of them needs a n variable. Or I am wrong, not sure ...
Aug 21 '08 #5
Banfa
9,065 Recognized Expert Moderator Expert
May I ask why you are not just using a vector?
Aug 21 '08 #6
arnaudk
424 Contributor
However I want to use it outside the member function also.
So then why are you making a local redeclaraion (see reply #4)? Remove "double* " from line 18. Even better, use an initializer list:
Expand|Select|Wrap|Line Numbers
  1. MyClass::MyClass(int _n) : A(new int[_n])
  2. {
  3.      n=_n;
  4.      if (!A) abort();
  5.      A[0]=0.0;A[1]=10.0;A[2]=20.0;A[3]=30.0;
  6. // etc
  7. }
  8.  
Aug 21 '08 #7
runn
4 New Member
May I ask why you are not just using a vector?
Thank you for answers. I am new to C++ and want to learn its basic rules at the beginning. Actually I want to write a matrix class and use it for scientific computing. They say vector class is not fast especially for small matrices. There may be a class from blitz which is fast. I can use it, but later.

So then why are you making a local redeclaraion (see reply #4)? Remove "double* " from line 18. Even better, use an initializer list
Because I didnt know how to allocate memory from inside the constructor. Thank you for pointing out initializer list. The code works now.
Aug 21 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

7
1576
by: andylcx | last post by:
Hi all, I have a question about the code below. Any idea abuot that, thanks in advance! myclass.h class myclass { public: myclass(); ~myclass(); void setdata();
5
14115
by: dam_fool_2003 | last post by:
Hai, I studied that the array size is fixed. But I come across a word called "variable length array". Is it possible to change the array size? So I tried the following: #include<stdio.h> #include<stdlib.h> int main(void) { int y = { 7, 9,10},i; for (;i<20;i++)
11
4473
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to accomplish. // - - - - - - - - begin code - - - - - - - typedef int sm_t; typedef int bg_t; sm_t sm; bg_t bg;
19
3155
by: Tom Jastrzebski | last post by:
Hello, I was just testing VB.Net on Framework.Net 2.0 performance when I run into the this problem. This trivial code attached below executed hundreds, if not thousand times faster in VB 6.0 than in .Net environment, under VS 2005 Beta 2. Does anyone have any idea whether this will be addressed in the final release? Thanks, Tomasz
9
2073
by: Peter Olcott | last post by:
// // Array2D.h 2005-11-27 5:50 AM // #define UINT unsigned int // // // class ArrayType2D { private: int Width;
5
355
by: mickey | last post by:
I know this may sound ridiculous but I need sanity check. I am developing in c++ for an embedded device where memory is tight and I have a class which always upon initialization dynamically allocates a 10kb buffer. Since this type of class object is always dynamically allocated, I am wondering if there is any advantage to allocating the buffer dynamically. I am thinking the buffer can simply be defined and statically allocated as a class...
7
3170
by: Sam | last post by:
Hello I have a structure called Company. struct Company { char *employee; char *employee_address; }; I want to build an array of this structure but the number of employees will change thorughout the course the programs use so it will need to
6
3566
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows uncaught exception. How to catch an exception that happened before main() try { ... } catch (...) { ... } block? Is there a way?
7
3118
by: alternative451 | last post by:
Hi, I have just one question : how to know the size of an array, i have un little program, i use first static, ant i can use sizeof() to know the size, but when i put it as paremeter in the function, size of return "1". ex int tab; printf("%d",sizeof(tab)/sizeof(int)); // print 10 int length(int *tab)
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10228
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7565
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4141
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.