Need a little help
Jul 27, 2013 at 4:23pm UTC
I am working through a book on c++.
I copied this code out of the book but I am getting an issue on the line containing the operator overloading function prototype. Any help as to why I am having issues would be helpful. I copied it right out of the book.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
class Critter
{
public :
Critter(const string& name = "" , int age = 0); //constrcutor protype
~Critter(); //deconstructor prototype NEW
Critter(const Critter& c); //copy constructor protoype NEW
Critter& Critter::operator =(const Critter& c);
void Greet() const ;
private :
string* m_pName;
int m_age;
};
Critter::Critter(const string& name, int age)
{
cout << "Constructor called\n" ;
m_pName = new string(name);
m_age = age;
}
Critter::~Critter()
{
cout << "Destructor called!\n" ;
delete m_pName;
}
Critter::Critter(const Critter& c) //Copy constructor definition
{
cout << "Copy constructor called\n" ;
m_pName = new string(*(c.m_pName));
m_age = c.m_age;
}
Critter& Critter::operator =(const Critter& c)
{
cout << "Overloaded assignment operator called!\n" ;
if (this != &c)
{
delete m_pName;
m_pName = new string (*(c.m_pName));
m_age = c.m_age;
}
return *this ; //very new stuff
}
void Critter::Greet() const
{
cout << "I'm " << *m_pName << " and I'm" << m_age << " years old.\n" ;
cout << "&m_pName: " << cout << &m_pName << endl;
}
//Global function prototypes
void testDestructor();
void testCopyConstructor(Critter aCopy);
void testAssignmentOp();
int main()
{
testDestructor();
cout << endl;
Critter crit("Poochie" , 5);
crit.Greet();
testCopyConstructor(crit);
crit.Greet();
cout << endl;
testAssignmentOp();
return 0;
}
void testDestructor()
{
Critter toDestroy("Rover" , 3);
toDestroy.Greet();
}
void testCopyConstructor(Critter aCopy)
{
aCopy.Greet();
}
void testAssignmentOp()
{
Critter crit1("crit1" , 7);
Critter crit2("crit2" , 9);
crit1 = crit2;
crit1.Greet();
cout << endl;
Critter crit3("crit" , 11);
crit3 = crit3;
crit3.Greet();
}
Jul 27, 2013 at 4:45pm UTC
Can you post what the error says?
Jul 27, 2013 at 4:48pm UTC
There must be
Critter& operator=(const Critter& c);
in the class definition instead of
Critter& Critter:: operator=(const Critter& c);
Jul 27, 2013 at 4:59pm UTC
Well, then I guess the book was wrong? Because I was thinking that! The error said something along the lines of extra declaration of critter. I think I hate operator overloading stuff. It is not explained very well in this book. ha
Topic archived. No new replies allowed.