Thread: Passing Objects, Constructors, Pointers, References, Values ???

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    66

    Question Passing Objects, Constructors, Pointers, References, Values ???

    Hello once again my friends. I have a problem here. I cannot understand the use of the constructor,destructor,and copy constructor. What are these things ? Do I need these ? How am I suppose to know the time they called ?

    This is my first misunderstanding. Let's solve this and then we move on to the next.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Before you get into constructors, destructors and copy constructors, you really should make sure you know what a class is and why you would use it.

    A constructor is a way to initialize a class. If you have a class which has an integer x, you may want to give x a value when an object of that class is instantiated. That is what a constructor is for.

    A deconstructor is when you want to delete an object. Let's say you have an object which has a file open. If that object is deleted, you want to make sure you close the file, right? If it allocated dynamic memory, you want to make sure that memory is deallocated (ie. free()'ed in C, delete'ed in C++), right? This is what a deconstructor can do. It can deallocate resources upon object destruction (or technically right before it).

    A copy constructor is a bit more detailed, but it's the idea of writing a special constructor to make a copy of itself. By default a "shallow copy" is performed in C++, and sometimes this is not desirable, so a copy constructor is created to perform a "deep copy". You can research this later, but this is not always needed.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    In classes, there are three types of special functions:
    Cosntructors - these are called to initialize your objects. They are called when first create your class. Their purpose is to make your class ready to use. Typically like a string constructor can take a const char* pointer to put that string into your string class.
    Copy constructor is called when you try to copy your object, such as obj1 = obj2. Its job is to make sure that the copy is successfully done. The compiler generates a default one if you don't declare one, which copies all member of the class to the class your are copying into. If you need to change this behavior (for example if you have pointers as class members), then you overload this.
    A destructor is called when your object is being destroyed. Its purpose is to clean up and free any memory held by the class.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Registered User
    Join Date
    Aug 2007
    Posts
    66
    Ok. So, a Constructor is a special function that initialize the class.

    for example.
    Code:
    class SimpleCat
    {
                public:
                      SimpleCat();   //constructor
                      ~SimpleCat();   //deconstructor
    };
    
    SimpleCat::SimpleCat()
    {
              cout << "This is the constructor of the class..." << endl;
    }
    
    SimpleCat::~SimpleCat()
    {
           cout << This is deconstructor of the class..." << endl;
    }
    So if I try this: SimpleCat Frisky; The result should be ==> This is the constructor of the class...

    How can I delete an object in order to produce the output message of deconstructor ?


    PS:I am not at home, so I cannot compile to see what's the output. Here, there is no programming...it's a PC full of games and antiviruses...Home Home...sweet Home alabama :P lol

  5. #5
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    It will be destroyed at the end of the function if it is created on the stack.

    To test constructing and deconstructing objects, I would suggest you use dynamic memory (for a number of reasons).

    Code:
    SimpleCat *c = new SimpleCat();
    cout << "After construction...." << endl;
    delete c;
    cout << "After deletion....." << endl;
    That kind of thing.

  6. #6
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Or create an artificial scope with {}
    Code:
    int main()
    {
      {
        SimpleCat c;
        cout << "After construction...." << endl;
      } //c goes out of scope
      cout << "After deletion....." << endl;
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  7. #7
    Registered User
    Join Date
    Aug 2007
    Posts
    66
    I compiled this:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class SimpleCat
    {
                public:
                      SimpleCat();   //constructor
                      ~SimpleCat();   //deconstructor
    };
    
    SimpleCat::SimpleCat()
    {
              cout << "This is the constructor of the class..." << endl;
    }
    
    SimpleCat::~SimpleCat()
    {
           cout << "This is deconstructor of the class..." << endl;
    }
    
    int main()
    {
        SimpleCat c;
        cout << "Message after create object c" << endl;
        return 0;
    }
    The output:
    Code:
    This is the constructor of the class...
    Message after create object c
    This is the deconstructor of the class...

    As I thought, when I create the object, the object's class constructor is called. Then, when the main() returns, the deconstructor is automatically called. So, I don't have to delete c object manually. Should I ?

  8. #8
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Manually delete it if you manually allocate it. If it's automatic on the stack as local function variables, no you don't have to delete anything.

    You still need a deconstructor, however, if you need the object to free up resources.

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Is there such a thing as a deconstructor? Or are they only destructors?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Yeah, deconstructor.... destructor.... I need to get my terms straight.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by BlackSlash12 View Post
    As I thought, when I create the object, the object's class constructor is called. Then, when the main() returns, the deconstructor is automatically called. So, I don't have to delete c object manually. Should I ?
    The general rule is: if you create the object on the stack (SimpleCat myCat) it will be destroyed when the function ends.
    If you create it on the heap using new (SimpleCat* pMyCat = new SimpleCat), then you must explicitly free it using delete (delete pMyCat), otherwise the object will never be destroyed and the destructor will never be called.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Aug 2007
    Posts
    66
    OK, I got the point. What about copy constructor ? Could you please, give me a similar source code example ?

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Bad code.
    Last edited by Elysia; 12-14-2007 at 02:45 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Eh, actually, that invokes the copy assignment operator. This is an example that invokes the copy constructor:
    Code:
    class MyClass
    {
    public:
    	MyClass(const MyClass& rMyClass); // Copy constructor
    };
    
    int main()
    {
        MyClass a;
        MyClass b(a); // Invokes copy constructor
    }
    Of course, in this case the compiler provided copy constructor will work just fine since... there's nothing to copy.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by Elysia View Post
    Code:
    class MyClass
    {
    public:
    	MyClass(const MyClass& rMyClass); // Copy constructor
    };
    
    int main()
    {
    	MyClass a;
    	MyClass b;
    	a = b; // Invokes copy constructor
    }
    Actually it doesn't. It'll invoke the assignment operator. That's why classes that overload the copy constructor should also overload the assignment operator.

    The copy constructor is called in any case where a copy of the class is needed, except the above.

    On the other hand, this does call the copy constructor:
    Code:
    class MyClass
    {
    public:
    	MyClass(const MyClass& rMyClass); // Copy constructor
    };
    
    int main()
    {
    	MyClass a;
    	MyClass b = a;// b is copy constructed from a.
            MyClass c(a); // alternate syntax for the above. Some say this is less ambiguous.
    }
    EDIT: laserlight beat me to it.
    Last edited by King Mir; 12-14-2007 at 02:47 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning an Array of Pointers to Objects
    By randomalias in forum C++ Programming
    Replies: 4
    Last Post: 04-29-2006, 02:45 PM
  2. Pointers to objects on the heap
    By foot in forum C++ Programming
    Replies: 3
    Last Post: 07-21-2005, 12:20 PM
  3. pointers in arrays... Declaring objects in a loop.
    By Guest852 in forum C++ Programming
    Replies: 10
    Last Post: 04-05-2005, 06:57 AM
  4. Pointers and references...
    By SushiFugu in forum C++ Programming
    Replies: 6
    Last Post: 12-08-2001, 04:21 PM
  5. Passing objects
    By Wiggin in forum C++ Programming
    Replies: 1
    Last Post: 10-17-2001, 08:00 AM