Home > Back-end >  Conditional constructor calling in C
Conditional constructor calling in C

Time:08-16

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.

CodePudding user response:

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))
{
}
  •  Tags:  
  • c
  • Related