Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ constructor call another constructor based on parameter type

Tags:

c++

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

like image 587
Tiago Peczenyj Avatar asked Jan 06 '13 16:01

Tiago Peczenyj


1 Answers

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 */ }
};
like image 128
Oliver Charlesworth Avatar answered Oct 14 '22 18:10

Oliver Charlesworth