Thread: constructors in classes

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

    constructors in classes

    Hello,

    I'm studying a C++ book, and I find it very confusing in the constructors and deconstructors in classes. What are they? Like this is a code from the book:

    class Bow
    {
    string color;
    bool drawn;
    int numOfArrows;

    Bow(string aColor);
    ~Bow()

    void draw();
    int fire();
    };

    can someone tell me what constructors and destrucors do, and what do they do in this code? thank you.

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    A constructor constructs an object and a destructor destroys an object. Its that simple. You can have many constructors but only one destructor. This says that there are many ways to make an object but only one way to destroy them.

    A constructor has the same name as the class. If it takes no parameters then it is a default constructor. If it takes a single parameter of type const yourclass& then it is a copy constructor. The destructor is denoted by the tilde symbol and also has the name of the class. So for class yourclass the destructor would be ~yourclass()
    The easiest way to learn about constructors and destructors is to put cout messages in them and step thru your code line by line in a debugger and watch what happens. See when each get called and work out why.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    3
    But why do you need them?

  4. #4
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    If you don't specify a constructor a default constructor is used when creating objects. Simply put you need some type of constructor when creating objects. It is used to initialize parameters within the object when created.

  5. #5
    *******argv[] - hu? darksaidin's Avatar
    Join Date
    Jul 2003
    Posts
    314
    Originally posted by Stoned_Coder
    A constructor constructs an object and a destructor destroys an object. Its that simple. You can have many constructors but only one destructor. This says that there are many ways to make an object but only one way to destroy them.
    Is it really that simple? If the constructor were a part of the object, how could it be used to construct that very object ?

    The egg or the chicken ?

    However, thats just a theoretical problem, if at all. Basically it's correct: You use the constructor to create the object.

    I don't know if there is an explanation for it in C++. In Delphi you always call a constructor as "a method of a class", therefore it's not really part of the object [like instance = classname.constructorname(parameter)].

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Constructors are part of the class. Not part of an object. None of the code of a class is truly part of the object; the object is really nothing more than one instance of the data members of the class. The methods which form the class, including the constructor and destructor, are used to make, manipulate, and destroy objects, but they aren't the objects themselves.

  7. #7
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    Code:
    class myclass
    {
    public:
    myclass() { cout<<"myclassval=0"; myclassval=0; }
    myclass(int val) { cout<<"myclassval=val"; myclassval=val; }
    ~myclass(){cout<<"destructing";}
    private:
    int myclassval;
    };
    
    int main(void)
    {
    myclass x;
    myclass y(20);
    }

    Is it more clear?
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  8. #8
    Registered User
    Join Date
    Jul 2003
    Posts
    3
    Originally posted by JaWiB
    Code:
    class myclass
    {
    public:
    myclass() { cout<<"myclassval=0"; myclassval=0; }
    myclass(int val) { cout<<"myclassval=val"; myclassval=val; }
    ~myclass(){cout<<"destructing";}
    private:
    int myclassval;
    };
    
    int main(void)
    {
    myclass x;
    myclass y(20);
    }

    Is it more clear?
    Yes. Thank you. This is much clearer

  9. #9
    Grammar Police HybridM's Avatar
    Join Date
    Jan 2003
    Posts
    355
    It's important to know that when you are writing a class, it doesn't exist, so in your class declaration you can't have:
    Code:
    class myclass
    {
         int x = 10;  // error
    
    };
    instead you might do:
    Code:
    class myclass
    {
         int x;
    public:
         myclass() { x = 10; }
    };
    So a constructor (among other things) gives you a way to initialise your variables before doing anything else when you create an object.
    Thor's self help tip:
    Maybe a neighbor is tossing leaf clippings on your lawn, looking at your woman, or harboring desires regarding your longboat. You enslave his children, set his house on fire. He shall not bother you again.

    OS: Windows XP
    Compiler: MSVC

  10. #10
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    here's another example:
    Code:
    class thisClass
    {
       public:
          thisClass();
          thisClass(int);
       private:
          int thisVariable;
    };
    thisClass::thisClass()
    {
       thisVariable=0;
    }
    thisClass::thisClass(int variableFromMain)
    {
       thisVariable=variableFromMain
    }
    
    int main()
    {
       ...
       thisClass classObject;
       thisClass classObjectVariable(32);
    
       cout<<classObject.thisVariable<<endl;  //outputs "0"
       cout<<classObjectVariable.thisVariable<<endl;   //outputs "32"
       ...
    }
    hope that makes it clearer why you can have more than one constructor...
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  11. #11
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    Is it really that simple? If the constructor were a part of the object, how could it be used to construct that very object ?

    The egg or the chicken ?

    However, thats just a theoretical problem, if at all. Basically it's correct: You use the constructor to create the object.

    I don't know if there is an explanation for it in C++. In Delphi you always call a constructor as "a method of a class", therefore it's not really part of the object [like instance = classname.constructorname(parameter)].
    That's mostly it; although in C++ the member functions (methods) of an object are the ones of that class. The code inside member functions is stored in one place, usually unaltered through the program's execution. Whenever an object wants to call a member function, it calls that code. (There's a secret argument, the 'this' pointer, which is passed with every member function. 'this' is a pointer which points to the object that "owns" the method. Hopefully that makes things clearer...)

  12. #12
    Grammar Police HybridM's Avatar
    Join Date
    Jan 2003
    Posts
    355
    Can I just ask a small question?

    Why do people do this with classes:
    Code:
    class myclass
    {
    public:
         myclass() { x = 20; }
    
    private:
         int x;
    };
    Why do functions first instead of variables, if you do variables first you save yourself a "private:" and it doesn't really affect readability either way, is there something I don't know about?

    EDIT: The egg came first, something laid an egg and from that egg a bird emerged which can be classed as a chicken.
    Last edited by HybridM; 07-27-2003 at 09:51 PM.
    Thor's self help tip:
    Maybe a neighbor is tossing leaf clippings on your lawn, looking at your woman, or harboring desires regarding your longboat. You enslave his children, set his house on fire. He shall not bother you again.

    OS: Windows XP
    Compiler: MSVC

  13. #13
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    It's just style. Most people put the interface first, then the implementation. In fact, many experienced programmers use the "pimpl idiom" to hide the entire implementation behind a "compilation firewall". For example:

    Code:
    // file MyClass.h
    
    class MyClass{
    public:
      MyClass(/*...*/);
      MyClass(const MyClass &);
      ~MyClass();
      MyClass& operator=(const MyClass &);
    private:
      struct Impl;
      Impl * pImpl;
    };
    Code:
    // file MyClass.cpp
    
    struct MyClass::Impl{
      int x;
      float y;
    }
    
    // Rest of the implementation
    In this way, the implementation and interface are totally separate, and any change to the implementation will affect only one .cpp file, reducing compile time drastically on large, interdependant projects. It also often drastically reduces header interdependance; the header file can get away with many fewer #includes.

    Plus, you can make a library, and only the public interface of the object is exposed to the users.
    Last edited by Cat; 07-27-2003 at 10:02 PM.

  14. #14
    Grammar Police HybridM's Avatar
    Join Date
    Jan 2003
    Posts
    355
    not sure if I was clear, unless I didn't understand what you said (likely).

    What I meant was, as classes default to private why would you put public stuff first and private after that? It seems more logical to do it the other way.
    Thor's self help tip:
    Maybe a neighbor is tossing leaf clippings on your lawn, looking at your woman, or harboring desires regarding your longboat. You enslave his children, set his house on fire. He shall not bother you again.

    OS: Windows XP
    Compiler: MSVC

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by HybridM
    not sure if I was clear, unless I didn't understand what you said (likely).

    What I meant was, as classes default to private why would you put public stuff first and private after that? It seems more logical to do it the other way.
    There is no right or wrong way. For example, this is perfectly valid:
    Code:
    class Foo
    {
            int x;
        public:
            void setX( int toThis ) { x = toThis; }
        private:
            int y;
        public:
            void setY( int toThis ) { y = toThis; }
    
        ...repeat over and over...
    };
    However, the reason people put the public information first is so you can see the interface, and not worry about the internals. Example:
    Code:
    class Foo
    {
        public:
            void setFoo( type value );
            void setBar( type value );
            type getFoo( void );
            type getBar( void );
    
        private:
            //stuff here
    };
    If you want to see right off what you can do with this class, the interface tells you that you can set and get two objects. Why would I care what the private internals of this object were, when all I want to do is set and get some thing when using this class?

    Anyway, that's the basic idea behind it.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Classes and constructors help please
    By S_Diggy in forum C++ Programming
    Replies: 7
    Last Post: 08-27-2007, 12:03 PM
  2. classes and overloading constructors
    By barneygumble742 in forum C++ Programming
    Replies: 2
    Last Post: 09-14-2005, 05:32 AM
  3. Destructors and Constructors on classes
    By Da-Nuka in forum C++ Programming
    Replies: 14
    Last Post: 06-14-2005, 02:08 PM
  4. Classes: constructors, destructors ???
    By mbeisser21 in forum C++ Programming
    Replies: 18
    Last Post: 07-21-2002, 09:33 PM
  5. Replies: 2
    Last Post: 01-15-2002, 06:00 PM