0

I have a set of classes. The underlying classes are difficult for a user to utilize, and violate the encapsulation design scheme: the user must know how the underlying code works in order to initialize the class.

Instead, I am trying to create a constructor wrapper for the inherited class's constructor. Here is a minimal example of what I am trying to do.

#include <iostream>
#include <vector>
using namespace std;
class classA{
public:
    int a;
    int b;
    explicit classA(int a,int b){
        this->a = a;
        this->b = b;
    }
};
class classB{
public:
    int a;
    int b;
    explicit classB(int a,int b){
        this->a = a;
        this->b = b;
    }
};

class classC{
public:
    vector<classA> a_team;
    vector<classB> b_side;
    explicit classC(vector<classA> vca,vector<classB> vcb){
        this->a_team = vca;
        this->b_side = vcb;
    }

};

class SpecificClass:public classC{
    using classC::classC;

Now, how would I add an additional constructor, to make the code more usable in a particular setting:

    SpecificClass(classA ca, classA ca2, classB cb){  // <---------- This fails
        // somehow, I call:
        classC({ca,ca2},{cb});
    }

    // How do I do this ^^^^ (C++11)
};
int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Not that the lines in question which do not compile are:

SpecificClass(classA ca, classA ca2, classB cb){  // <---------- This fails
    // somehow, I would initialize the class here after
    // interpreting the inputs...
    classC({ca,ca2},{cb});
}

How would I implement this functionality in C++11?


So the answer:

The way the notation works is wrapper_function(parameters) -> constructor function.

In place of the lambda notation's arrow is the :, where the second half of the ternary conditional operator, and one half of the scope resolution operator is used as if it is in set notation (or, more likely, an English language colon), and in the place of traditional function notation (probably chosen in order to avoid confusion with the pointer notation).

So, this is a one off, alternative-notation lambda function mapping the inputs to the constructor.

Chris
  • 28,822
  • 27
  • 83
  • 158

0 Answers0