lundi 22 juin 2020

How to initalize nested class members in outer class constructor in C++

I have a program in C++ that has a nested class as shown below

class Outer{
Outer(int val);
private:
    class Inner;
    std::unique_ptr<Inner> obj;

};
Outer::Outer(int val):obj(Inner::CreateInstance(val)) 
{

}

My Inner class is in another file and has a private string variable mystring as shown

class Inner{
public:
    Inner(int val):mVal(val), mystring(""){
    }
    static std::unique_ptr<Inner> CreateInstance(int val){
    // returns Inner unique ptr
    }
private:
    int mVal
    string mystring;
};

Here mVal and mystring is already initialized in Inner class constructor. But I get this MISRA error that says mystring is not initialized in Outer constructor.

How do I initialize mystring from Outer constructor? Even though Inner class initialized the mystring then why do I get this kind of error.

Aucun commentaire:

Enregistrer un commentaire