How to define a class in Arduino?

ArduinoHardwareSoftware & Coding

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.


class Student
      Student(char division, int roll_no);
      void add_science_marks(int marks);
      int get_roll_no();
      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:
   Student Yash('A',26);

   Serial.print("Roll number of the student is: ");

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


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.

Published on 30-Jul-2021 15:03:46