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.