Dynamic Memory Allocation Question

This is a discussion on Dynamic Memory Allocation Question within the C++ Programming forums, part of the General Programming Boards category; I'm trying to create a class called "Employee" that holds two character arrays, "firstName" and "lastName". class Employee { private: ...

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    1

    Dynamic Memory Allocation Question

    I'm trying to create a class called "Employee" that holds two character arrays, "firstName" and "lastName".

    class Employee
    {
    private:
    char *firstName;
    char *lastName;
    float hourlyRate;
    float weeklyPay;
    public:
    void setFirstName(char *);
    char* getFirstName();
    void setLastName(char *);
    char* getLastName();
    void setHourlyRate(float hr);
    float getHourlyRate();
    void computeWeeklyPay();
    float getWeeklyPay();
    Employee();
    ~Employee();
    };
    I need to allocate memory for the firstName and lastName fields in the constructor. I keep getting a compiler error when I try the following code:

    Employee::Employee()
    {
    firstName = new char[];
    lastName = new char[];
    }
    If I specify a size in the [] braces, it compiles correctly, but that seems to be defeating the purpose of dynamically allocating memory. Is there any way to get this to work without putting in an array size? None of the books or online tutorials I've seen, give any examples that use character arrays. Any help would be appreciated.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Is there any way to get this to work without putting in an array size?
    Use std::strings instead of character arrays or dynamic allocation.

    >but that seems to be defeating the purpose of dynamically allocating memory
    The point being that you can get the size at run-time and then later resize the memory if you need to. As opposed to being stuck with a fixed size chosen at compile-time for arrays.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A question related to dynamic memory allocation
    By spiit231 in forum C Programming
    Replies: 2
    Last Post: 03-11-2008, 01:25 AM
  2. Another Question...memory allocation
    By quickclick330 in forum C Programming
    Replies: 4
    Last Post: 12-12-2007, 04:25 PM
  3. dynamic memory allocation problem
    By firyace in forum C Programming
    Replies: 4
    Last Post: 05-23-2007, 10:57 PM
  4. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 06:04 PM
  5. dynamic allocation question
    By vale in forum C++ Programming
    Replies: 1
    Last Post: 08-26-2001, 05:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21