-
I think it's logic error
Code:
#include<iostream>
#include<string>
using namespace std;
class Account {
private :
double Balance ;
string BlanceType ;
public :
Account(){}
Account (double d) {
Balance = d;
BlanceType = "Bronze" ; }
void Set ( double B ) {
Balance = B ;
if ( Balance>= 20000 )
{ BlanceType = "Golden" ;}
if ( Balance>= 5000 )
{ BlanceType = "Silver" ; }
else
{ BlanceType = "Bronze" ; } }
int GetBalance ( ) {
return Balance ; }
string GetBalanceType ( ) {
return BlanceType ; }
void Show(){ cout << Balance<< BlanceType; }
};
class Customer{
private:
int numberOfac........s;
Account *Ac........s;
public:
Customer(int number)
{
numberOfac........s = number;
Ac........s = new Account[numberOfac........s];
for (int i=0;i<numberOfac........s; i++)
{ double p;
cout<<"Enter balence ";
cin>>p;
Ac........s[i].Set(p);
}}
~Customer(){delete []Ac........s;}
Customer operator ++(int)
{Customer c=*this;
numberOfac........s++;
return c;
}};
int main()
{
int number;
cout<<"Enter number of ac........s";
cin>>number;
Customer custom(number);
custom++;
return 0;
}
output
Enter number of ac........s3
Enter balence 120000
Enter balence 2000
Enter balence 2000
aasd(1335) malloc: *** error for object 0x100200: double free
*** set a breakpoint in malloc_error_break to debug
aasd(1335) malloc: *** error for object 0x100150: double free
*** set a breakpoint in malloc_error_break to debug
-
You are dynamically allocating memory for your array in your class and destroying it in the destructor. The fact that you need the destructor is a good indication that you also need a copy constructor and a copy assignment operator (see the Rule of Three).
The problem is that when you create a copy of your object inside operator++, the copy does a shallow copy which only copies the pointer. Since you now have two objects pointing to the same location, when one of those objects goes out of scope the memory is deleted. If the other copy tries to use it then you get a crash (or some other error).
The best solution is to use vector instead of dynamically allocating your array. The only good reason I've heard for manually allocating your array is if your instructor won't allow you to use vector (which is too bad but not something you can usually control).
If you don't use vector for whatever reason, then you need to create a copy constructor and copy assignment operator that properly copy the object.
-
ok i'll try use copy constructor
but there is something missing in this code and i'm trying to solve it
i have to increment a custmer account if he has at least one golden account and i have to write it
in main can you help me please?
-
You may want to fix your indentation first. Your code is unreadable.