Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional constructor calling in C++

In the following code

#include <iostream>

enum class motorid{
    M1,
    M2
};
enum class encoderid{
    E1,
    E2
};
class encoder{
public :
    encoder(encoderid eid):Eid(eid){}
private:
    encoderid Eid;
};
class motor{
    public:
    motor(motorid mid):Mid(mid){
        if(mid == motorid::M1){
            e(encoderid::E1);
        }
        e(encoderid::E2);
    }
    private:
    motorid Mid;
    encoder e;
}

I want to initialize encoder class with value based on value given to motor class from main, I don’t want to expose the encoder details to main,but I am forced to give the encoder type also. How to achieve this? Since no heap is involved using new and creating object is not an option.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Syntax would be:

motor(motorid mid):Mid(mid), e(mid == motorid::M1 ? encoderid::E1 : encoderid::E2)
{
}

For more complex case (or for readability), creating function might help:

encoderid create_encoderid(motorid mid)
{
    if (mid == motorid::M1){
        return encoderid::E1;
    }
    return encoderid::E2;
}

motor::motor(motorid mid):Mid(mid), e(create_encoderid(mid))
{
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading