Reputation: 77
I have made an application in c++ where the user writes some random numbers (which are placed in an array) and are displayed to him, and, using the copy constructor, his input age is displayed again. But the problem here is that the copy function executes, but it doesn't display any information. Here is my code:
#include <iostream>
#include <string>
using namespace std;
class Identity{
protected:
int* arry_int;
int ages;
Identity(){} //private default constructor
public:
Identity(int repeated_number){ //overloaded constructor
ages = repeated_number ;
arry_int = new int [ages];
}
void getAge(){ //getting age form the user
for (int i = 0; i < ages; i++){
cout << "Enter age[" << i << "]: ";
cin >> arry_int[i];
}
}
void printAge(){
cout << "Friend's ages" << endl;
cout << "-----------------" << endl;
for (int i = 0; i < ages; i++){
cout << arry_int[i] << endl;
}
}
//move copy constructor
Identity(Identity&& cpy){
cout << "Declaring move constructor" << endl;
arry_int = cpy.arry_int;
cpy.arry_int = NULL;
}
//move assignment operator
Identity& operator=(Identity&& cpy){
cout << "Declaring move assignment operator" << endl;
if (this != &cpy){
delete arry_int;
arry_int = cpy.arry_int;
cpy.arry_int = NULL;
}
return *this;
}
~Identity(){
delete arry_int;
}
};
int main(){
string nemesis;
Identity iden(5);
iden.getAge();
iden.printAge();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Enter your nemesis name: " << endl;
getline(cin,nemesis);
//nemesis stealing your identit
Identity stolen(move(iden));
cout << "Now " << nemesis << " stole your friend's age and used it against you" << endl;
stolen.printAge();
system("pause");
return 0;
}
Upvotes: 1
Views: 581
Reputation: 310960
You forgot to copy data member ages in the move constructor.
There must be
//move copy constructor
Identity(Identity&& cpy){
cout << "Declaring move constructor" << endl;
arry_int = cpy.arry_int;
cpy.arry_int = NULL;
ages = cpy.ages;
}
The same is valid for the move assignment operator
//move assignment operator
Identity& operator=(Identity&& cpy){
cout << "Declaring move assignment operator" << endl;
if (this != &cpy){
delete arry_int;
arry_int = cpy.arry_int;
cpy.arry_int = NULL;
ages = cpy.ages;
}
return *this;
}
Also the destructor shall be defined as
~Identity(){
delete []arry_int;
}
And it is unknown why you declared the default constructor as protected.
Upvotes: 3