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.

thx

Post a Reply

Replies

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;
 public:
   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
Thanks
0 Alekro A · August 29, 2014
Thanks Adam i understand now :)
  • 1

C++

107,310 followers
About

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

Links
Moderators
Bucky Roberts Administrator