devxlogo

Defining behavior in one constructor, then letting two others call it

Defining behavior in one constructor, then letting two others call it

Question:
I defined a class A, which has three constructors:

A(), A(int), A(int, int)
Can I just define the behavior in one constructor, say A(int, int), and let the other two constructors call A(int, int)?

I can do that in Java.

For example,

public class A{  public A()  {    this(1, 2);  }  pub A(int i)  {    this(i, 2);  }  public A(int i, int j)  {    c = i + j;  }  public int c;}
How do I do that in C++? And will it allocate the variables twice in C++?

Answer:
Cool idea, but unfortunately you can’t do that. You can, however, apply one of two solutions. You can overload the constructor in a manner similar to what is being illustrated in your code sample, but instead of attempting to call one constructor from the other, you can create a private helper function that all constructors call, thus giving you the same effect (see code extract below).

#include class A{// Constructorspublic:	A( );	A(int);	A(int , int);// Operationspublic:	int getTotal();// Helper functionprivate:	void Init(int, int);// Attributesprivate:	int c;};A::A( ){	Init( 1, 2 );}A::A(int i){Init( i, 2 );}A::A(int i, int j){	Init( i, j );}void A::Init(int i, int j){	c =3D i + j;}int A::getTotal(){	return c;}void main(){	A myA1;	A myA2(5);	A myA3(5, 4);	cout << "myA1 total: " << myA1.getTotal() << endl; 	// myA1 total: 3	cout << "myA2 total: " << myA2.getTotal() << endl;	// myA2 total: 7cout << "myA3 total: " << myA3.getTotal() << endl;	// myA3 total: 9}
A more elegant alternative is to create a constructor with default parameters. Check out the code extract below:
#include class A{// Constructorpublic:	A(int i =3D 1, int j =3D 2);// Operationspublic:	int getTotal();private:	int c;};A::A(int i, int j){	c =3D i + j;}int A::getTotal(){	return c;}void main(){	A myA1;	A myA2(5);	A myA3(5, 4);	cout << "myA1 total: " << myA1.getTotal() << endl; 	// myA1 total: 3	cout << "myA2 total: " << myA2.getTotal() << endl;	// myA2 total: 7cout << "myA3 total: " << myA3.getTotal() << endl;	// myA3 total: 9}
The C++ compiler will automatically overload the constructor applying the same body of code in all cases. Just imagine the compiler generating the following overloaded constructors:
A::A( ){	c =3D 1 + 2;}A::A(int i){	c =3D i + 2;}A::A(int i, int j){	c =3D i + j;}
In any case, you can see the elegance of default parameters if used appropriately as opposed to function-overloading, be it constructors or regular member functions.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist