Skip to main content
GameDev.net gamedev.net
🔒 Locked

Default constructors

Started by pdstatha Jun 18, 2002 at 11:11 AM 5 replies 200+ views
Original Post
pdstatha
pdstatha
How does one know when to use a default constructor or not???
xg0blin
xg0blin
If when you make an instance of your class you don''t put any values in for your constructor, if you have default values, they will be put in instead, thus you''re default constructor
Oluseyi
Oluseyi
quote:
Original post by xg0blin
If when you make an instance of your class you don''t put any values in for your constructor, if you have default values, they will be put in instead, thus you''re default constructor.

No. A default constructor is provided by the compiler when you provide none, or a zero-parameter constructor provided by you that is generally called to instantiate implicit and temporary objects.
pdstatha
pdstatha
Ok bare with me, i''ve written a "Peg" class that is basically representing a stack. I defined this in my header file, when adding to the stack the element that is being added cannot be of greater size than the current top element. Does the following look right, or have I not grasped constructors yet?


  
class CPeg{
public:
CPeg(stack<int> pStack,const string& itsName):
pegStack(pStack),name(itsName)
{}
~CPeg();
int addRing(int rSize){
if(rSize < pegStack.top()){
pegStack.push(rSize);
return OK;
}else
return FAILED;
}
void removeRing(){ pegStack.pop(); }
private:
stack<int> pegStack;
string name;
};


So if I were to create an instance of a peg in my main cpp file, would that constructor be correct, or do I not need the "stack pStack" bit???
pdstatha
pdstatha
*bump*
Oluseyi
Oluseyi
quote:
Original post by pdstatha
So if I were to create an instance of a peg in my main cpp file, would that constructor be correct, or do I not need the "stack<int> pStack" bit?

With the given constructor, you can do this:
CPeg myPeg( new stack<int>, "myPeg" ); 

You cannot, however, do this:
CPeg myOtherPeg; 

The immediately preceding code snippet is what default constructors are for. Generally, a compiler will attempt to provide a default constructor which merely zeroes out the structure, but one should oneself provide a constructor that takes no arguments for such instances. This no-argument constructor is the default constructor.
nyStagmus
nyStagmus
One thing I like to do to keep myself from making the mistake of using the default constructor when I want myself to always use a non-zero-parameter constructor is to put a zero-parameter constructor in private or protected. That way the compiler will give you an error and you are sure that you will never have uninitialised classes.

/nystagmus

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.