Page 1 of 1

Need Help With Copy Constructor

Posted: Mon Dec 09, 2002 12:00 am
by Jerry B.
Can someone help me understand a copy constructor?  I am trying to write an example for myself, so I can understand it.  What am I doing wrong here?

#include <iostream>

using namespace std;

class Tree
{
        public:
                Tree();
                int setAge(int);
                Tree(const Tree&);
                void printAge();

        private:
                int* age;
};


Tree::Tree()
{
        *age=30;
}

int setAge(int age)
{
        cout << "Please enter the tree's age...\n";
        cin >> age;
        return age;
}

Tree::Tree(const Tree& firstTree)
{
        age = new int;
        *age=*(firstTree.age);
}

void printAge()
{

        cout << age;
}

int main()
{
        Tree first;
        first.setAge(30);
        first.printAge();
        getchar();
        return 0;
}

RE:Need Help With Copy Constructor

Posted: Tue Dec 10, 2002 12:00 am
by eox
hi, try these modifications:

#include <iostream>

using namespace std;

class Tree
{
        public:
                Tree();
                ~Tree();
                int setAge(int);
                Tree(const Tree&);

                void printAge();

        private:
                int* age;
                Tree operator =(const Tree&);   // prevents you from using
};    // second = first. if you do this, first gets copyed bitwise -> you
      // get _identical_ objects -> you have two times the same age-pointer
      // problem: if first gets deconstructed, second.age points to an
      // invalid memory address


Tree::Tree()
{
    age = new int;                // XXX - you first have to allocate some mem
    *age=30;                      // before you can write to it...
}

Tree::~Tree()
{
delete age;              // we don't want some memory leaks, do we?..
}

int Tree::setAge(int age)         //XXX   Tree::
{
        cout << "Please enter the Tree's age...\n";
        cin >> age;
        return age;
}

Tree::Tree(const Tree& firstTree)
{
        age = new int;
        *age= *(firstTree.age);
}

void Tree::printAge()             //XXX   Tree::
{

        cout << *age << "\n";     //XXX   * if you want to see the value of *age
}                                 // without * you get the pointer-value

int main()
{
        Tree first;
        first.setAge(30);
        first.printAge();

        Tree second(first);  //XXX  just to test the copy constructor
        second.printAge();   //XXX
        // second = first;  doesn't work :)
        getchar();
        return 0;
}