dimanche 30 octobre 2016

Separate implementation and header in c++ class

I created a test class in a test.cpp file and it works well. When I moved all the class from the cpp file to a header (hpp) file my executable did not link (multiple instances of some functions declaration problem).

So having the following class, what can be placed in the header file and what needs to move in my source (cpp) file in order to avoid link errors?

class MyClass {
public:

    MyClass(int record, const std::string& myType, int age, Education* education = 0, int categ = 0, int winningAmount = 0) : record_(record), myType_(myType), age_(age), education_(education), categ_(categ), winningAmount_(winningAmount) {}

    MyClass(const MyClass& rhs) : record_(rhs.record_), myType_(rhs.myType_), age_(rhs.age_),  education_(0), categ_(rhs.categ_), winningAmount_(rhs.winningAmount_)  { 
        education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_); 
    }

    virtual ~MyClass();

    MyClass& operator=(const MyClass& rhs) {
        if (this == &rhs)
            return *this;
        delete education_;

        record_ = rhs.record_;
        myType_ = rhs.myType_;
        age_ = rhs.age_;
        education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_);
    categ_ = rhs.categ_;
    winningAmount_ = rhs.winningAmount_;
        return *this;
    }

    template <typename Appender>
    void Serialize(Appender& appender) const {

        appender.StartObject();

    appender.String("record");
        appender.Int(record_);

        appender.String("myType");
        appender.String(myType_);

    appender.String("age");
        appender.Int(age_);

        appender.String("education");
        if (education_)
            education_->Serialize(appender);
        else
            appender.Null();

        appender.EndObject();
    }

private:

    int record_;
    std::string myType_;
    int age_;
    Education *education_;
    int categ_;
    int winningAmount_;

};

MyClass::~MyClass() {
    delete education_; 
}

Aucun commentaire:

Enregistrer un commentaire