How to define a class in Arduino?


You can define a class in Arduino just like in C, with public and private variables and methods.The example below demonstrates the definition of a Student class, which has the constructor,two methods (add_science_marks and get_roll_no) and 3 private variables, _division, _roll_no and _science_marks.

Example

class Student
{
   public:
      Student(char division, int roll_no);
      void add_science_marks(int marks);
      int get_roll_no();
   private:
      char _division;
      int _roll_no;
      int _science_marks;
};

Student::Student(char division, int roll_no){
   _division = division;
   _roll_no = roll_no;
}

void Student::add_science_marks(int marks){
   _science_marks = marks;
}

int Student::get_roll_no(){
   return _roll_no;
}

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   Student Yash('A',26);

   Serial.print("Roll number of the student is: ");
   Serial.println(Yash.get_roll_no());
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor output is shown below −

The class declaration in the above code could have well been within a Student.h file, and the function definitions within Student.cpp file. This way, you can define your own library in Arduino.

Updated on: 30-Jul-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements