Like any other function, a constructor can also be overloaded with more
than one function that have the same name but different types or number
of parameters. Remember that for overloaded functions the compiler will
call the one whose parameters match the arguments used in the function
call. In the case of constructors, which are automatically called when
an object is created, the one executed is the one that matches the
arguments passed on the object declaration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
// overloading class constructors
#include
using namespace std;
class CRectangle {
int width, height;
public:
CRectangle ();
CRectangle (int,int);
int area (void) {return (width*height);}
};
CRectangle::CRectangle () {
width = 5;
height = 5;
}
CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
int main () {
CRectangle rect (3,4);
CRectangle rectb;
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
|
rect area: 12
rectb area: 25
|
In this case,
rectb was declared without any arguments, so it
has been initialized with the constructor that has no parameters, which
initializes both
width and
height with a value of 5.
Important: Notice how if we declare a new object and we want to
use its default constructor (the one without parameters), we do not
include parentheses
():
1
2
|
CRectangle rectb; // right
CRectangle rectb(); // wrong!
|
Comments
Post a Comment
https://gengwg.blogspot.com/