C++ constructors

+2 Alekro A · August 27, 2014
In Buckys 14 C++ tutorial he says that constructros are very important but he doesnt say what they are used for. I know what a constructor is but i just cant think of any way to use it.
I would be very gald if you could explain to me why they are so important and of what use they are.


Post a Reply


Oldest  Newest  Rating
+2 Franz Schmidt · August 27, 2014
For example you can make a counter for your objects you create with the class 
And also you can use this counter to give every object a specific id.
+1 Adam Beck · August 29, 2014
Here is a simple way to use them. This sets the length and width for a rectangle.

// example: class constructor
#include <iostream>
using namespace std;

class Rectangle {
   int width, height;
   Rectangle (int,int);
   int area () {return (width*height);}

Rectangle::Rectangle (int a, int b) {
 width = a;
 height = b;

int main () {
 Rectangle rect (3,4);
 Rectangle rectb (5,6);
 cout << "rect area: " << rect.area() << endl;
 cout << "rectb area: " << rectb.area() << endl;
 return 0;
0 Alekro A · August 27, 2014
0 Alekro A · August 29, 2014
Thanks Adam i understand now :)
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator