I have this class
class XXX {
public:
XXX(struct yyy);
XXX(std::string);
private:
struct xxx data;
};
The first constructor (who works with a structure) is easy to implement. The second I can parte one string in a specific format, parse and I can extract the same structure.
My question is, in java I can do something like this:
XXX::XXX(std::string str) {
struct yyy data;
// do stuff with string and extract data
this(data);
}
Using this(params) to call another constructor. In this case I can something similar?
Thanks
The term you're looking for is "constructor delegation" (or more generally, "chained constructors"). Prior to C++11, these didn't exist in C++. But the syntax is just like invoking a base-class constructor:
class Foo {
public:
Foo(int x) : Foo() {
/* Specific construction goes here */
}
Foo(string x) : Foo() {
/* Specific construction goes here */
}
private:
Foo() { /* Common construction goes here */ }
};
If you're not using C++11, the best you can do is define a private helper function to deal with the stuff common to all constructors (although this is annoying for stuff that you'd like to put in the initialization list). For example:
class Foo {
public:
Foo(int x) {
/* Specific construction goes here */
ctor_helper();
}
Foo(string x) {
/* Specific construction goes here */
ctor_helper();
}
private:
void ctor_helper() { /* Common "construction" goes here */ }
};
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