In C++ I'm attempting to emulate how Java handles calls to it's constructor. In my Java code, if I have 2 different constructors and want to have one call the other, I simply use the this
keyword. Example:
public Constructor1(String s1, String s2)
{
//fun stuff here
}
public Constructor2(String s1)
{
this("Testing", s1);
}
With this code, by instantiating an object with Constructor2 (passing in a single string) it will then just call Constructor1. This works great in Java but how can I get similar functionality in C++? When I use the this
keyword it complains and tells me 'this' cannot be used as a function
.
This will be possible in C++11 with constructor delegation:
class Foo {
public:
Foo(std::string s1, std::string s2) {
//fun stuff here
}
Foo(std::string s1) : Foo("Testing", s1) {}
};
You can write an init
private member function for such job, as shown below:
struct A
{
A(const string & s1,const string & s2)
{
init(s1,s2);
}
A(const string & s)
{
init("Testing", s);
}
private:
void init(const string & s1,const string & s2)
{
//do the initialization
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With