1

I have searched about class and int but I still don't understand.

I have seen this code online I want to understand it

class Motor { 

  int enablePin;
  int directionPin1;
  int directionPin2;
  public: 

  //Method to define the motor pins
  Motor(int ENPin,int dPin1,int dPin2){
    enablePin = ENPin;
    directionPin1 = dPin1;
    directionPin2 = dPin2;
}; 
4
class Motor {

This says to start defining a class. A class is like a "container" that holds both data and functions (methods). After defining the class, it becomes like a new variable type that you can declare multiple instances of.

  int enablePin;
  int directionPin1;
  int directionPin2;

These define the 3 integer variables (int=integer; whole numbers like 2, 3, 1000, -5, etc.) that belong to the class and have the identifiers given (enablePin, etc.) Since not otherwise specified, these variables are private, meaning that only other functions in the class can access them. Other parts of the program are not allowed to access these variables.

public:

This means that the following definitions are accessible by parts of the program that exist outside the class.

Motor(int ENPin,int dPin1,int dPin2) {
  enablePin = ENPin;
  directionPin1 = dPin1;
  directionPin2 = dPin2;
}

This defines the only "member function" in this class and because it shares the same name as the class (Motor), it is called a "Constructor", and allows you to pass arguments to an object created from the class -- in this case, if you declare an object of class Motor by myMotor = Motor(1, 2, 3);, the constructor is called with parameters 1, 2, and 3. This constructor happens to just set the private variables to be the same as the arguments passed in.

But... All of this is basic C++, so a book or course on C++ programming would be better in-depth resource to understand this.

The code snippet also is incorrect because it has unbalanced curly-braces -- there is one to open the definition of the class and one to open the definition of the constructor, but only one closing brace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.