Thread: Question about Constructors

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    36

    Question about Constructors

    Hi.
    I have a question about Constructors and how they are used.
    After working through "C++ without fear" (great book btw) until getting to the part that explains classes, I decided to experiment a bit.
    The plan is to create a simple Console program that simulates the logic of firing a shotgun.
    Anyway I go this so far (which works as intended: It basically sets the magazine sizes for the two "instances" (is that the correct word?) of CBaseShotgun and prints them out.

    Code:
    //Shotgun Class Test
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    #define MOSSBERG_MAG 6
    #define REMINGTON_MAG 5
    
    //Declare shotgun class
    class CBaseShotgun {
    private:
    	int magsize;
    	bool needpump;
    public:
    	int getmagsize();
    	void setmagsize(int newmagsize);
    };
    
    
    //Init The new shotgun thingies
    CBaseShotgun CMossberg;
    CBaseShotgun CRemington;
    
    
    //Main function
    //Sets the Magazine Sizes and prints them out
    int main() {
    	CMossberg.setmagsize(MOSSBERG_MAG);
    	cout<<CMossberg.getmagsize()<<endl;
    	
    	CRemington.setmagsize(REMINGTON_MAG);
    	cout<<CRemington.getmagsize()<<endl;
    
    		return 0;
    }
    
    
    
    //Function definitions
    int CBaseShotgun::getmagsize()	{
    	return magsize;
    }
    
    void CBaseShotgun::setmagsize(int newmagsize) {
    	magsize = newmagsize;
    }

    Now I am not asking how to add more functionality to the program or something. I am wondering what the use for Constructors and Destructors is. I do not really get what they are and what they are for. After all this little program does work and I have no clue about onstructors and Destructors. I have carefully read the section about them in the book and the tutorials about them on this site. But I simply do not get what they are for.... and if I have to use them in a situation like this.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Jefff
    //Init The new shotgun thingies
    CBaseShotgun CMossberg;
    CBaseShotgun CRemington;
    It looks like you are using the convention of a 'C' prefix for class names, so here it looks like you are under the impression that you are creating two classes. However, you are actually creating two objects of the CBaseShotgun class, and these objects are default constructed.

    If you provided an appropriate constructor for the CBaseShotgun class, you create the two objects with the desired initial values instead of default constructing them and then assigning those values.
    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

  3. #3
    Registered User
    Join Date
    Jul 2009
    Posts
    36
    1) The C is something I picked up while looking at some Game Source Code and they appear to use the same convention. I guess my assumption was wrong.

    . However, you are actually creating two objects of the CBaseShotgun class, and these objects are default constructed.
    So these things I called "instances" of the "baseclass" are called objects? I hope i am not throwing around too much false terminology here.

    However, you are actually creating two objects of the CBaseShotgun class, and these objects are default constructed.

    If you provided an appropriate constructor for the CBaseShotgun class, you create the two objects with the desired initial values instead of default constructing them and then assigning those values.
    So a constructor is basically something that "initializes" the new object with its own set of default "data members"?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Jefff
    The C is something I picked up while looking at some Game Source Code and they appear to use the same convention.
    That is fine. My point is that the convention is used to denote class names, not instance names. If you do not use a convention as is conventional, then the convention becomes useless, and possibly even harmful.

    Quote Originally Posted by Jefff
    So these things I called "instances" of the "baseclass" are called objects?
    Yes. "Instance" is also a correct term.

    Quote Originally Posted by Jefff
    So a constructor is basically something that "initializes" the new object with its own set of default "data members"?
    Yes, though it is not necessarily a default set since the values may well be provided as arguments to the constructor.
    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

  5. #5
    Registered User
    Join Date
    Jul 2009
    Posts
    36
    Code:
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    #define MOSSBERG_MAG 6
    #define REMINGTON_MAG 5
    
    //Declare shotgun class
    class CBaseShotgun {
    private:
    	int magsize;
    	bool needpump;
    public:
    
    	//Constructors
    	CBaseShotgun() {}
    	CBaseShotgun(int newmagsize) {setmagsize(newmagsize);}
    		
    	//Other Member Functions
    	int getmagsize();
    	void setmagsize(int newmagsize);
    
    };
    
    
    //Init The new shotgun thingies
    CBaseShotgun CMossberg(6);
    CBaseShotgun CRemington(5);
    
    
    //Main function
    //Sets the Magazine Sizes and prints them out
    int main() {
    
    	cout<<CMossberg.getmagsize()<<endl;
    	
    
    	cout<<CRemington.getmagsize()<<endl;
    
    		return 0;
    }
    
    
    
    //Function definitions
    int CBaseShotgun::getmagsize()	{
    	return magsize;
    }
    
    void CBaseShotgun::setmagsize(int newmagsize) {
    	magsize = newmagsize;
    }
    Ok after your explanation it starts to make sense. Above is the updated example which does work.

    Code:
    	
    //Constructors
    	CBaseShotgun() {}
    	CBaseShotgun(int newmagsize) {setmagsize(newmagsize);}
    So this is a correctly created constructor?

  6. #6
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Your "get" member functions (or really any member function that does not alter the object) should be declared as const.
    Code:
    //Declare shotgun class
    class CBaseShotgun {
        ...
    		
        //Other Member Functions
        int getmagsize() const;
    
    };
    
    
    ...
    
    
    //Function definitions
    int CBaseShotgun::getmagsize() const	{
       return magsize;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  7. #7
    Registered User
    Join Date
    Jul 2009
    Posts
    36
    Is there a special meaning to use const? The Book I use did not mention this yet, and the program appears to work without any issues.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Jefff
    So this is a correctly created constructor?
    Yes, but I would use a constructor initialisation list instead. Consider:
    Code:
    // Shotgun class
    class CShotgun {
    public:
        // Constructors
        explicit CShotgun(int newMagSize) : magSize(newMagSize) {}
    
        // Other Member Functions
        int getMagSize() const;
        void setMagSize(int newMagSize);
    private:
        int magSize;
        //bool needpump;
    };
    
    #include <iostream>
    
    // Creates the shotguns and prints them out
    int main() {
        using namespace std;
    
        const int mossbergMagSize = 6;
        const int remingtonMagSize = 5;
    
        CShotgun mossberg(mossbergMagSize);
        CShotgun remington(remingtonMagSize);
    
        cout << mossberg.getMagSize() << endl;
        cout << remington.getMagSize() << endl;
    
        return 0;
    }
    
    //Function definitions
    int CShotgun::getMagSize() const {
        return magSize;
    }
    
    void CShotgun::setMagSize(int newMagSize) {
        magSize = newMagSize;
    }
    I renamed CBaseShotgun to CShotgun as the "Base" does not appear useful. I removed the default constructor since a "default shotgun" does not appear to make sense (but if it does, you should initialise the member variables). I declared the constructor explicit so as to prevent:
    Code:
    CShotgun mossberg = mossbergMagSize;
    Then, what you see with the colon is a constructor initialisation list that initialises magSize to newMagSize. Speaking of which, I have chosen to demonstrate the camel case naming convention for variable and function names.

    Note that I declared the getMagSize() member function as const since it logically does not modify the observable state of the CShotgun object.

    Notice also that I have changed the macros into const variables, and moved the global objects into the main function.
    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

  9. #9
    Registered User
    Join Date
    Jul 2009
    Posts
    36
    Code:
    explicit CShotgun(int newMagSize) : magSize(newMagSize) {}
    This looks a bit cryptic to me, but mostly because this syntax and the keyword explicit were not yet used in the book I have.
    Thx for the info.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  2. A question about class members and constructors
    By Megidolaon in forum C++ Programming
    Replies: 5
    Last Post: 01-30-2009, 03:01 PM
  3. question about constructors and exceptions
    By Elkvis in forum C++ Programming
    Replies: 3
    Last Post: 12-05-2008, 06:15 PM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  5. Replies: 2
    Last Post: 12-17-2001, 06:40 PM