Is it possible to perform multiple initializations with one constructor?

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Rectangle
{
	public:
		explicit Rectangle( int initialWidth = 0, int initialLength = 0, 
int initialArea = 0; int initialParameter = 0) : 
                               storedWidth{ initialWidth } { }, 
                               storedLength{ initialLength } { }, storedArea{ initialArea } { }, 
                               storedPerimeter{ initialPerimeter } { };
		
		
	
	private:
		int storedWidth;
		int storedLength;
		int storedArea;
		int storedPerimeter;
		
}


Can I do this? I am having a difficult time finding if it is okay to have a constructor take more than one parameter and then perform more than one initialization.
Last edited on
Can I do this?

What does your compiler say? If it compiles without errors or warnings your next step is to run the program and test the the initialization.

Fair enough. I was just wondering if someone knew offhand. I will test it and post what I find here.
Yes, you can initialize multiple variables in the constructor, but you can only have one constructor body, and it has to be after the whole initialization list.
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;
};
Last edited on
Topic archived. No new replies allowed.