Classes: constructors, destructors ???

This is a discussion on Classes: constructors, destructors ??? within the C++ Programming forums, part of the General Programming Boards category; I've recently been reading all about classes, but I'm having a hard understanding what the constructor and destructor member functions ...

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    3

    Angry Classes: constructors, destructors ???

    I've recently been reading all about classes, but I'm having a hard understanding what the constructor and destructor member functions are and what the heck they do. Can anyone explain this to me or point me to a link that does? Thanks in advance.

    -Mbeisser21

  2. #2
    Registered User
    Join Date
    Apr 2002
    Posts
    1,571
    Okay, I will try to explain a little, then if you have any questions just post back. Take the following code for example.
    Code:
    class CPoint
    {
        private:
          int m_x;
          int m_y;
    };
    There is a simple class for a point, not terribly interesting. Now I didn't explicity declare my destructor and contructor because there are default ones supplied for you if you do not specify one. I could specify mine own like this.
    Code:
    class CPoint
    {
        private:
          int m_x;
          int m_y;
    
        public:
          CPoint();   // Constructor
          ~CPoint(); // Destructor
    };
    The constructor is called when the class variable is created or instantiated. The destructor is called either when the variable goes out of scope, or you call delete on a pointer variable.

    If i wanted to though, I could make my own special constructor. Take this code.

    Code:
    // CPoint.h file...
    class CPoint
    {
        private:
          int m_x;
          int m_y;
    
        public:
          CPoint( int x, int y );   // Constructor
          ~CPoint(); // Destructor
    };
    
    // CPoint.cpp file   (implementation of class)
    #include "CPoint.h"
    
    CPoint::CPoint( int x, int y )
    {
        m_x = x;
        m_y = y;
    }
    
    CPoint::~CPoint( )
    {
    }
    I don't know if that really clears anything up but perhaps. If you have more specific questions just ask.
    "...the results are undefined, and we all know what "undefined" means: it means it works during development, it works during testing, and it blows up in your most important customers' faces." --Scott Meyers

  3. #3
    Registered User billholm's Avatar
    Join Date
    Apr 2002
    Posts
    225

    Lightbulb

    Hello newbie!

    Constructors and destructors, basically, are just functions like the others you can include within your class. The only difference is, they are sometimes invoked automatically (and in a subtle way).
    Isn't that cool?

    Anyway, here's the trick:

    1) Everytime you declare a class object in some function, the constructor is invoked and whatever you place inside that will be read and statements are executed. Ideally, the constructor must contain initializers for your private and protected data in your class.

    2) Everytime you leave the a block statement in which you have declared a class object, the destructor is invoked. The block statements could be anything inside curly braces (functions are block statements too). Be careful though; when I said it leaves a block, I meant that it enters the "opening" curly brace '{' and leaves the "closing" curly brace '}'. If you just made a jump to some other block without finishing the previous object-containing block, the destructor will not be automatically invoked.

    Aside from that fact, destructors can also be manually invoked (like placing a statement that calls the destructor). You can use this if you intend to jump out of a block and you find that the object in the previous block is no longer useful.

    If you have further questions, don't hesitate to ask. That's the only way to learn effectively.
    All men are created equal. But some are more equal than others.

    Visit me at http://www.angelfire.com/my/billholm

  4. #4
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    You can delete it easily, just go to edit and then hit delete.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  5. #5
    Registered User billholm's Avatar
    Join Date
    Apr 2002
    Posts
    225
    (Click!) ...and post has been deleted!
    All men are created equal. But some are more equal than others.

    Visit me at http://www.angelfire.com/my/billholm

  6. #6
    Registered User
    Join Date
    Jul 2002
    Posts
    3
    Aha thanx guys that clears up a lot. I think i get it now.

    -Mbeisser21

  7. #7
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    Sorry guys, there are a few things here that have to be said:

    The only difference is, they are sometimes invoked automatically (and in a subtle way).

    That's utter rubbish. When an object is instantiated, is it constructed ie. the constructor is called. There is nothing 'subtle' about it at all, and it's not something that happens 'sometimes', it happens all the time. If you have defined a constructor (which you should always do even if it doesn't do anything), it WILL get called when your object is instantiated.

    Same goes for destructors. When an object goes out of scope, or is 'delete'd the destructor WILL be called (there are exceptions when people are using polymorphism and haven't declared destructors as virtual, in which case some destructors may not be called, but that's just bad programming). Whether you like it or not it gets called. Again, there's nothing subtle here.

    destructors can also be manually invoked

    yes they can, but you should NEVER EVER do this. There is no need for it. If you have code in the destructor that you wish to execute at other times, then put it in another function, and call that from the destructor. Don't ever call the destructor directly.

    cheers
    U.
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

  8. #8
    Unregistered
    Guest
    >>That's utter rubbish. When an object is instantiated, is it constructed ie. the constructor is called. There is nothing 'subtle' about it at all, and it's not something that happens 'sometimes', it happens all the time. If you have defined a constructor (which you should always do even if it doesn't do anything), it WILL get called when your object is instantiated.

    Same goes for destructors. When an object goes out of scope, or is 'delete'd the destructor WILL be called (there are exceptions when people are using polymorphism and haven't declared destructors as virtual, in which case some destructors may not be called, but that's just bad programming). Whether you like it or not it gets called. Again, there's nothing subtle here. <<


    Why do you say it's rubbish? Lets look at it this way:

    Yes the constructor is always called. But sometimes, if you don't declare a constructor, your code may still compile smoothly because the compiler will create an auto-constructor for you. So this means that if you can create classes without necessarily have to 'write' a constructor for it. The fact that the compiler does the job for seems subtle enough don't you think so?

    After all, when newbies practice making classes, they don't really realize at first the necessity of a constructor. So they don't immediately see the hidden ability of the compiler.

    What I just explained about the constructor goes for the destructors too. The compiler does the job without having to notify the programmer.

    So you say that the object is destroyed if the object goes out of scope? Picture this:

    If I made objects that require the 'new' operator for their private data, the objects will remain in memory until the counterpart 'delete' operator is reached. Now what if I had to call another function and I will never ever be going back to the previous function. The object will never be destroyed and the private data remain in memory. The 'delete' operator has to be put in the destructor for it to effectively manipulate the class's private data. So the destructor has to be manually invoked. Memory space is precious.

    Well I think I have explained it in a simple way. I sure hope I enlightened you.

  9. #9
    Registered User billholm's Avatar
    Join Date
    Apr 2002
    Posts
    225
    (Oh shoot! Dammit it happened again) Sorry about that. That unregistered post is mine. My login time expired so my name wasn't reflected.
    All men are created equal. But some are more equal than others.

    Visit me at http://www.angelfire.com/my/billholm

  10. #10
    Registered User
    Join Date
    Jul 2002
    Posts
    273

    Talking

    ACTUALLY, I'm going to throw a whole bomb into the mix!

    There is a case where constructors and destructurs would not be called!

    try this:

    Code:
    MyClass *test;
    
    test = (MyClass*)new char[sizeof(MyClass)];
    test->SomeMemberFunction();
    delete [] (char *)test;
    this is 100% legal and the constructors and destructors do not get called! what do you think about that?

  11. #11
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    this is 100% legal and the constructors and destructors do not get called! what do you think about that?
    I think : That's not C++.

    It's totally immoral!

    BUT then again, it's legal and nobody's stopping you.

  12. #12
    Registered User
    Join Date
    Jul 2002
    Posts
    273
    Agreed! It is totally, morally unbearable.

    But everyone's talking about absolutes and I know there is at least this exception to the rule.

    Sorry 'bout dat

  13. #13
    Registered User
    Join Date
    Jul 2002
    Posts
    273
    oh and if it's part of C, it's part of C++

  14. #14
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    Originally posted by Hershlag
    ACTUALLY, I'm going to throw a whole bomb into the mix!

    There is a case where constructors and destructurs would not be called!

    try this:

    Code:
    MyClass *test;
    
    test = (MyClass*)new char[sizeof(MyClass)];
    test->SomeMemberFunction();
    delete [] (char *)test;
    this is 100% legal and the constructors and destructors do not get called! what do you think about that?
    Yeah but that's just trying to fool the compiler......and you wouldnt do that purposely...Your just calling the constructor of a char (which if it has one does very little) and casting the memory reference back to your pointer...its what's after new that has its constructor called.....

    Cool though

    Code:
    #include <iostream>
    using namespace std;
    
    class Class1{
    public:
    	Class1(){cout << "Class1 constructor" << endl;}
    	~Class1(){cout << "Class1 destructor" << endl;}
    };
    
    class Class2{
    public:
    	Class2(){cout << "Class2 constructor" << endl;}
    	~Class2(){cout << "Class2 destructor" << endl;}
    };
    
    int main()
    {
    	Class1* MyClass;
    	MyClass = (Class1*)new Class2;
    	delete (Class2*)MyClass;
    	return 0;
    }
    Last edited by Fordy; 07-16-2002 at 01:20 PM.

  15. #15
    Banned frenchfry164's Avatar
    Join Date
    Oct 2001
    Posts
    1,552
    you have too much time on your hands

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Constructors and Destructors
    By lasher in forum C++ Programming
    Replies: 2
    Last Post: 12-03-2006, 10:53 PM
  2. Destructors and Constructors on classes
    By Da-Nuka in forum C++ Programming
    Replies: 14
    Last Post: 06-14-2005, 02:08 PM
  3. constructors in classes
    By Kenman in forum C++ Programming
    Replies: 16
    Last Post: 07-28-2003, 07:35 AM
  4. Constructors and Destructors
    By GravtyKlz in forum C++ Programming
    Replies: 7
    Last Post: 03-09-2003, 09:44 AM
  5. Replies: 2
    Last Post: 01-15-2002, 05:00 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21