As any fan of Mexican food knows, whenever you make yourself a burrito, you always go through the same sequence of steps to build your burrito out of prime beef, a tortilla, and any other toppings you choose. And when using classes in your programs, you will probably find that whenever you create a new instance of a class, you always go through the same steps of calling a couple of methods to initialize the data in the object. While this works all well and good, it does get on ones nerves to have to type the same thing over and over again. As you may have figured out by now, the fact that we're talking about this means that yep, there is a nice solution to this problem in C++. In C++, you can define a special method in a class called a constructor which is called when you create a new instance of a class. This constructor can take parameters just like any other method. Here's a comparison of a class with a constructor and a class without a constructor: Without Constructorclass Taco { public: void SetBeefAmount(int ounces) { beefamt = ounces; } void SetToppingAmount(int ounces) { toppingamt = ounces; } private: int beefamt; int toppingamt; }; void main(void) { Taco supreme; supreme.SetBeefAmount(10); supreme.SetToppingAmount(1); } With Constructorclass Taco { public: Taco(int beefounces, int toppingounces) { beefamt = beefounces; toppingamt = toppingounces; } private: int beefamt; int toppingamt; }; void main(void) { Taco supreme(10, 1); } Although this is a fairly simple example, it shows some of the keys of how to declare and use constructors. There are a couple of key things to note in the above example:
Also, note that the constructor is called as soon as the class is created. In the above example, that would be on the line containing the class declaration. However, if you were to have a pointer to a class, it's constructor would not be called until you allocate memory for what that pointer points to, when you call new. |