Classwide Scope

04 Sep 2011

I am trying to create and instantiate an I2CSlave object visible to an entire class only. In C++, when you declare the object, the constructor has to run. What I want to do is declare the object in classwide space and have my I2CCommandReceiver class instantiate the I2CSlave object. Whatever I try, the compiler throws an error. Its not as simple as C#, but there has to be a way to do it.

// Receiver class, throws errors.
class I2CCommandReceiver
{       
    public:
    I2CSlave I2C_Slave; // **** The I2CSlave constructor has to run here ****
    // Default constructor.  
    I2CCommandReceiver(int addr, PinName P1, PinName P2)
    {
        I2CSlave(P1, P2); // **** I want the I2CSlave to run here like C#. ****
        
        //I2C_Slave = I2CSlave(P1, P2); // I2C slave object. 
        //I2C_Slave.address(addr);
    }
};
04 Sep 2011

Hi Ben,

I think you are probably looking for something like this:

Calling constructor of member object within class

class I2CCommandReceiver {
public:
    I2CCommandReceiver(int addr, PinName P1, PinName P2) : I2C_Slave(P1, P2) {
        I2C_Slave.address(addr);
    }

    I2CSlave I2C_Slave;
};

Hope that helps,

Simon

06 Sep 2011

Thanks, it now works.