All bases and members of an object are initialized on construction of the object. Every constructor does that.
You thus ask, can you overload the constructor function to have other than one parameter versions.
The default constructor takes 0 parameters. That is the first sign of having other than one parameter.
http://www.cplusplus.com/reference/vector/vector/vector/ has (C++14) total of 10 constructors that take 0, 1, 2, or 3 parameters.
Therefore, the answer is
yes.
Notes on your Rectangle.
* Can I have a rectangle that has width==3, lenght==4, area==1, and perimeter==42? You do let me make one.
If the names you use match concepts in math, then that is a logical error.
If area==width*lenght is a class invariant, then your class must enforce it.
The area is easy to compute; you don't have to store it as a member variable. You could have it as member function.
If it were expensive to compute, then caching the result in member variable would make sense.
* Your semicolons are misplaced.
- Function's implementation does not end with semicolon. You have one.
- Class definition has to end with semicolon. You don't have one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
class Rectangle
{
public:
explicit Rectangle( int width = 0, int length = 0 )
: width{ width },
length{ length },
area{ width*length },
perimeter{ 2*(width+length) }
{} // body of constructor
private:
int width;
int length;
int area;
int perimeter;
};
|