Thread: allocating memory in constructor

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    allocating memory in constructor

    Hi, I have a question about allocating memory in constructor. For example consider simple
    class Array:
    Code:
    #include <iostream>
    using namespace std;
    
    class Array
    {
    	double* array;
    	int len;
    public:
    	Array(int);
    	void load();
    	void show();
    	~Array();
    };
    
    Array::Array(int i):len(i)
    {
    	array=new double[len];
    }
    void Array::load()
    {
    	cout<<"Enter elements: ";
    	for(int i=0;i<len;i++)
    	{
    		cin>>array[i];
    	}
    }
    void Array::show()
    {
    	for(int i=0;i<len;i++)
    		cout<<array[i]<<" ";
    }
    Array::~Array()
    {
    	delete [] array;
    }
    
    int main()
    {
    	Array a(5);
    	a.load();
    	a.show();
    }
    I've read somewhere that it's not good to have new in constructor because there is a possibility that under some circumstances process of memory allocation fails. In that case object will not be created in a propery way. How to handle this case? Should I write for example a new method create() and in constructor to leave just:
    Code:
    Array::Array(int i):len(i)
    {
    }
    Beacuse many of you have a lot more experience then I have I'm sure you're going to give me some good advices on this issue.
    Thanks very much!

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> How to handle this case?

    just catch the exception, ie:

    Code:
    try {
     // allocate something 
    } catch(std::bad_alloc foo) {
     // handle
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    So it is OK to leave new in constructor?

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    As long as you do some simple error handling, yes.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Allocating memory. constructor being called
    By steve1_rm in forum C++ Programming
    Replies: 2
    Last Post: 02-03-2009, 02:17 AM
  2. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  3. Dynamically allocating memory
    By abh!shek in forum C++ Programming
    Replies: 8
    Last Post: 02-21-2008, 09:59 AM
  4. dynamic memory allocating error
    By valhall in forum C Programming
    Replies: 2
    Last Post: 04-04-2003, 10:49 AM
  5. Replies: 5
    Last Post: 11-24-2002, 11:33 PM