1

I'm trying to create an array of objects in c++.

I'm creating a employee object, from my constructor in my company class here:

employee obj(int tempIdNum, double tempBase, double tempSales, double tempRate);

emp[tempcount]=obj;  (this doesn't work?)

Emp is the name of the array which is defined here, located in my company h file.

 Employee emp[4]; 

sorry commission =employee..... here is my commission(employee) class cpp

    using namespace std;


//----------------------------------------
//Name: default constructor
//Purpose: create a new object with attributes set to zero
//Parameters: none
//Returns: none
//----------------------------------------
Commission::Commission()
{
    //cout << "In default constructor of Commission class" << endl;
    idNum = 0;
    base  = 0.0;
    rate  = 0.0;
    sales = 0.0;
}


//----------------------------------------
//Name: initializing constructor
//Purpose: initialize all attributes
//Parameters:
//  idNum - new value for id Num
//  base -  new value for base amount
//  sales - new value for sales amount
//  rate -  new value for rate fraction
//Returns:  none  
//----------------------------------------       
Commission::Commission(int idNum, double base, double sales, double rate)
{
    //cout << "In initializing constructor of Commission class" << endl;
    this->idNum = idNum;    
    this->base  = base;
    this->sales = sales;
    this->rate  = rate;
}

//----------------------------------------
//Name: copy constructor
//Purpose: constructor a new object from an existing object
//Parameters: 
//  emp - current employee object
//Returns: none
//----------------------------------------
Commission::Commission(const Commission& emp)
{
    //cout << "In copy constructor of Commission class" << endl;
    idNum = emp.idNum;
    base  = emp.base;
    sales = emp.sales;
    rate  = emp.rate;
}

//----------------------------------------
//Name: operator=
//Purpose: The copy assignment method copies the rhs object
//  into the lhs object
//Parameters: 
//  rhs - object on the right hand side of the = sign
//Returns: nothing
//----------------------------------------
void Commission::operator=(const Commission& rhs)
{
    //cout << "In copy assignment of Commission class" << endl; 
    idNum = rhs.idNum;
    base  = rhs.base;
    sales = rhs.sales;
    rate  = rhs.rate;
}

//----------------------------------------
//Name: destructor
//Purpose: destruct object and print id num
//Parameters: none
//Returns: 
//----------------------------------------
Commission::~Commission()
{
    //cout << "In destructor of Commission class for id num: " << idNum << endl;
}

//----------------------------------------
//Name: setIdNum
//Purpose: set id num to a new value
//Parameters: 
//  newIdNum - new value for id num
//Returns: true if new id num is between 0 and 999, inclusively
//   otherwise false
//----------------------------------------
bool Commission::setIdNum(int newIdNum)
{
    if (newIdNum >= 0 && newIdNum <= 999)
    {
        idNum = newIdNum;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: setBase
//Purpose: set base to a new value
//Parameters: 
//  newBase - new value for base
//Returns: true if new base is greater zero; otherwise false
//----------------------------------------
bool Commission::setBase(double newBase)
{
    if (newBase > 0.0)
    {
        base = newBase;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: setRate
//Purpose: set the commission rate
//Parameters: 
// newRate - new commission rate as a percentage
//Returns: true if rate greater than zero and less than or equal to 0.20
//----------------------------------------
bool Commission::setRate(double newRate) 
{
    if (newRate > 0.0 && newRate <= 0.20)
    {
        rate = newRate;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: setSales
//Purpose: set sales to a new amount
//Parameters:
//  newSales - new amount of sales
//Returns: true if sales is greater than or equal to zero; otherwise false
//----------------------------------------
bool Commission::setSales(double newSales) 
{
    if (newSales >= 0.0)
    {
        sales = newSales;
        return true;
    }
    else
        return false;
}

//----------------------------------------
//Name: getIdNum
//Purpose: get the current id num
//Parameters: none
//Returns: current id num
//----------------------------------------
int Commission::getIdNum()  
{
    return idNum;
}

//----------------------------------------
//Name: getBase
//Purpose: get the current base amount of salary
//Parameters: none
//Returns: current base salary
//----------------------------------------
double Commission::getBase()  
{
    return base;
}

//----------------------------------------
 //Name: getRate
//Purpose: get the current commission rate as fraction
//Parameters: none
//Returns: current commission rate
//----------------------------------------
double Commission::getRate()
{
    return rate;
}

//----------------------------------------        
//Name: getSales
//Purpose: get current amount of sales
//Parameters: none
//Returns: current amount of sales
//----------------------------------------
double Commission::getSales()
{
    return sales;
}

//----------------------------------------
//Name: calcSalary
//Purpose: calculate commission as base + sales x commission rate
//Parameters: none
//Returns: amount of commission
//----------------------------------------
double Commission::calcSalary() 
{
    return (base + sales * rate);
}





and here is its .h


    #include <string>
using namespace std;

#ifndef Commission_H
#define Commission_H

class Commission
{
    private:
        int    idNum;   //id number of employee
        double base;    //base salary
        double rate;    //rate of commission as fraction
        double sales;   //sales on which commission rate applies

    public:
        //constructors
        Commission();               //default constructor
        Commission(int idNum, double base, double sales, double rate);  //constructor with idNum
        Commission(const Commission& orig);  //copy constructor

        //destructor
        ~Commission( );

        //copy assignment
        void operator=(const Commission& rhs);

        //mutators
        bool setIdNum(int idNum);        //set id num
        bool setBase(double base);       //set base salary
        bool setRate(double rate);       //set rate of commission
        bool setSales(double sales);     //set amount of sales for commission

        //accessors
        int    getIdNum();    //get id num;
        double getBase();     //get base salary
        double getRate();     //get commission rate
        double getSales();    //get sales for commission

        //calculate salary
        double calcSalary();  //calculate commission  
};        

#endif
tim22
  • 11
  • 1
  • 1
  • 4
  • tempcount is just a counter for a loop...depending on how many employees ther are – tim22 Jan 06 '11 at 07:17
  • 3
    How does it 'not work' ? Does not compile ? Breaks at execution ? Doesn't do what you expect ? – icecrime Jan 06 '11 at 07:19
  • sorry it does not compile...i get this: "46 E:\exercise2\Company.cpp no match for 'operator=' in '((Company*)this)->Company::emp[tempcount] = obj' " – tim22 Jan 06 '11 at 07:22
  • Highlight all your code and press CTRL+K to make it all readable and properly formatted. – Null Set Jan 06 '11 at 08:03
  • there u go sorry....first time posting – tim22 Jan 06 '11 at 08:04
  • I've checked your code and it works for me when I've changed name of the class from employee to Commission and when object was created using some concrete values. Commission emp[4]; Commission obj(1,2.1, 3.2, 4.3); emp[1]=obj; – Zuljin Jan 06 '11 at 08:35

7 Answers7

1

As stated by the error message : the employee class must have an accessible operator= for this code to compile. As you already probably already know, the compiler will declare a copy-assignment operator if you don't provide one yourself.

As for the reason of the error, I suspect that employee has const data members or anything else which makes the implicitly defined operator ill-formed (12.8/12) :

A program is illformed if the class for which a copy assignment operator is implicitly defined has:

  • a nonstatic data member of const type, or
  • a nonstatic data member of reference type, or
  • a nonstatic data member of class type (or array thereof) with an inaccessible copy assignment operator, or
  • a base class with an inaccessible copy assignment operator.
icecrime
  • 74,451
  • 13
  • 99
  • 111
0

I presume you declared the array as

employee emp[MAX];

so when you

employee obj(int tempIdNum, double tempBase, double tempSales, double tempRate);
emp[tempcount] = obj

here's what you did:

  1. create an object obj
  2. copy that object into emp[tempcount] object (think assignment operator).

about this part i'm not completely sure, but when you do

employee emp[MAX];

you actually create MAX employee objects (all using the default constructor).

jrharshath
  • 25,975
  • 33
  • 97
  • 127
0

The construction seems wrong. Delete the type specifiers:

Employee obj(tempIdNum, tempBase, tempSales, tempRate);

Or try:

emp[tempcount]=Employee(tempIdNum, tempBase, tempSales, tempRate);
Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96
  • ok, but wasnt that the purpose of employee obj(int tempIdNum, double tempBase, double tempSales, double tempRate); – tim22 Jan 06 '11 at 07:28
  • Edited, I missunderstood the problem. The object construction looked like a function declaration. – Juraj Blaho Jan 06 '11 at 07:29
  • when i delete the types compilers asks for them – tim22 Jan 06 '11 at 07:43
  • What is the error compiler gives, when you delete the types? Having the types there is invalid syntax. – Juraj Blaho Jan 06 '11 at 09:53
  • I tried your 2nd suggestion and it compiles, however the program crashes when run and all data is 0 – tim22 Jan 06 '11 at 10:30
  • The only issue now is that i have to Return a Commission object with the employee [one element of the Emp array]....im not entirely sure what this means? – tim22 Jan 06 '11 at 10:52
0

Maybe, you need to implement one "operator =" constructor function, like this:

Employee& Employee::operator =(const Employee& otheremp)
{
     // to be done ... 
}
JasonW
  • 1
  • 1
0

Last but not least. Try this:

employee array[100];

employee e(1,1.1,1.5,2.5);

array[0] = e;

should work

Arenim
  • 4,097
  • 3
  • 21
  • 31
0

Your copy assignment should not be void. Change it as follows:

Commission& Commission::operator=(const Commission& rhs)
{
    // bla bla
    return *this;
}

Or better yet, get rid of these all together. Compiler generated versions does the right thing and are simpler if all you are doing is copying members around (as in your case). This goes both for copy constructor, copy assignment, and the destructor. But make it explicit by adding a comment in your class declaration indicating that the class is using compiler generated copy constructor and assignment.

Let me give one last unsolicited advice: Please take your time to properly format your question, and make it concise. The reason you didn't get an answer right away for such a simple misuse is cause you have a lot of gunk in your post. For example, spend 5 minutes to search/replace Commission with Employee to improve consistency, truncate all of the clearly irrelevant methods and documentation.

sly
  • 1,722
  • 1
  • 10
  • 15
-2

It's not good to make array of objects. Much better is to make an array of pointers to objects.

employee ** array;
array = new employee[array_count]; // create an array of object pointers
for(int i=0; i<array_count; i++)
{
  array[i] = new employee( . . . your constructor parameters . . .);
  OR
  array[i] = *(anExistingEmployeeObject);
}

Please, don't forget to remove array safely:

for(int i=0; i<array_count; i++) delete array[i];
delete array;
Arenim
  • 4,097
  • 3
  • 21
  • 31
  • We havent learned pointers formely yet...so im dont really understand you code? – tim22 Jan 06 '11 at 07:37
  • 1
    And even better is not to use raw arrays, but `std::vector`. – Juraj Blaho Jan 06 '11 at 07:37
  • Juraj Blaho, they're sloooooooow :) – Arenim Jan 06 '11 at 07:43
  • 1
    @Arenim: Who told you `std::vector` is slow? Have you tried to disassemble raw array and vector code? Even if it would be slower for some implementation it is much simpler to use correctly. Your code has a memory leak or undefined behavior. – Juraj Blaho Jan 06 '11 at 07:51
  • @tim22, I told. i've made some tests when I've started to learn STL, and results was not good. In fact, STL itself is too low-level for such bad perfomance it provides. If You want something fast -- use C syntax. If You want something safe -- take a look on boost or QT. – Arenim Jan 06 '11 at 07:57
  • -1: "It's not good to make array of objects. Much better is to make an array of pointers to objects." This is bad advice both in general and specifically. In C++, you should not add indirection unless you need it, because it makes your life harder (in nicer languages, indirection tends to be added automatically whether you want it or not, and it's easy to deal with). And when you do need that indirection, you should be using smart pointers, a pointer-container, etc.... almost anything other than a raw pointer. Raw pointers are quite rare in well-written, modern C++. – Karl Knechtel Jan 06 '11 at 08:03
  • @Arenim: Don't know how did you tested (maybe without optimizations), but look at http://stackoverflow.com/questions/381621/using-arrays-or-stdvectors-in-c-whats-the-performance-gap . -1 – Juraj Blaho Jan 06 '11 at 08:04