Creating class and objects

in this example i think i mostly understand what they are trying to explain,

#include <iostream>
#include <string>
using namespace std;

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values
  myObj.myNum = 15;
  myObj.myString = "Some text";

  // Print values
  cout << myObj.myNum << "\n"; 
  cout << myObj.myString; 
  return 0;
}

but why create a class and then make objects when you can just make a struct and access it directly.

struct struct{
 int myNum = 15;
}struct s;

void loop{
s.myNum = 12;
Serial.println(s.myNum);
}

EDIT: this C++ OOP (Object-Oriented Programming) pretty much explains that. I would like to practice use more standard c++ on arduino. It would take me a while to learn i think but i like programming avr but i want to move on to something like the stm32/other cpu that use raw standard c and c++ in the future

To get the answer of your query, please explore internet for simple examples and get the meanings of all the words pointed by the arrows in the following class declaration.

2 Likes

If you want to really learn C++, then remain stick with Arduino UNO and practice simple programs from the tutorial sites of the net.

yes i did an exercise here, C++ Classes and Objects and i passed. but it dont explain everything that i can understand. for example, it wanted me to use a access specifier to make members of MyClass accessible from outside the class. so i tried to use global but it did not accept.

and why use global / private / public anyways. what are their purpose useful for?

I do plan on sticking to arduino. especially right now. i just would like to understand more.

Read the history behind the need of the development of C++ Language by Bjarne Stroustrup rover the standard C Language.

As discussed in the other thread You need to modify your diagram for class variable (at least)

You can also have a look here

https://www.cplusplus.com/doc/tutorial/

(And for classes https://www.cplusplus.com/doc/tutorial/classes/)

Of course the reference is always good to have at hand.
https://en.cppreference.com/w/cpp/language

1 Like

I have used functions a lot in my code. I learned classes can contain methods and objects. Im going to be converting my project from arduino mega "16" mhz to esp32 "240" mhz.

im going to have to redesign some of my code. This might give me a chance to use classes and and learn a few other things. I have a few days to study before my esp32s show up in the mail.

I stared with arduino core because i wanted to mess with the hardware and program hardware to do things and arduino has a lot of support

What is the point of access identifiers.

private members of a class are accessible only from within other members of the same class (or from their "friends").
protected members are accessible from other members of the same class (or from their "friends"), but also from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.

Why use private? or protected?

A class (classname) contains functions and variables. An object is created from classname. Functions of the classname are applied on objects and then the functions are termed as methods.

Example: (blinking of L (built-in LED of UNO) using class based codes

class DigitalIO  //ClassName (DigitalIO) is declared/created using class keyword
{
  private:
    int ledPin;  //variable can only be accessed by the functions under public: specifier

  public:
    DigitalIO(int powerpin): ledPin(powerpin) {} //inline constructor to initilize ledPin
    void ioDir();  //member functions
    void ledON();
    void ledOFF();
};

DigitalIO led(13);  //led is called object of type DigitalIO

void setup()
{
  Serial.begin(9600);
  led.ioDir();     //setting up the direction of IO line(13) as output; ioDir() is called method
}

void loop()
{
  led.ledON();
  delay(1000);
  led.ledOFF();
  delay(1000);
}

void DigitalIO::ioDir()   //member function definition; :: (double colon) is called scope resolution operator
{
  pinMode(ledPin, OUTPUT);
}

void DigitalIO::ledON()
{
  digitalWrite(ledPin, HIGH);
}

void DigitalIO::ledOFF()
{
  digitalWrite(ledPin, LOW);
}
1 Like

keeping the internal magic of a class within the class (not public) prevents anyone not allowed messing around with the variables for example and thus your methods (member functions) can trust nothing weird / unplanned has happened to them.

The user of the class needs to rely only on the proposed API for the class and so if you fix bugs or find a faster algorithm that requires to change everything inside the class, as long as you keep the API intact then everyone’s code relying on your class will keep working fine.

Encapsulation is one of the key concept of OOP

check out the article on Wikipedia for example

In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components.[1] Encapsulation is used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.

1 Like

you really dont need to do much at all, there is an esp 32 core for arduino. and it to your ide (arduino or platformio) and keep on coding. I literally just made the transition, few things to worry about with pin assignments & such, but its still C++.

really recommend the tutorials others have suggested. but you asked about accessing variables...
anything in the public section is accessible by classinstance.var2 or classinstance.methodX() for functions. Things inside of private can only be directly accessed from within the class itself. if you need something private, often you will see little helper functions(get, set, do): uint8_t getCount() { return count;}

other than the tutorials, just pop open some of the classes you already use & see how their set up...honestly, thats where I've learned most of what I know....though Im no expert.

maybe this is obvious, but classes are powerful, its worth the investment in learning how they work.

1 Like

No reason. A 'struct' is the same as a 'class' except the default access is 'public:' instead of 'private:'.

Note: You can't name your struct type 'struct' because 'struct' is a keyword. Call it something else. You also don't need to repeat the type:

struct foo {
 int myNum = 15;
} s;
1 Like

A large proportion of software engineering tools are simply there to abstract detail away so that you don't have to worry about it. To help you build a model in your head about what your system does without needing to remember every little thing that's going on.

So you program in C++, rather than assembler or (shudder) binary op codes and now for the most part, you don't care about the details of the CPU's instruction set.

You can write functions, and once they're debugged you can ignore how they perform their job and concentrate on other things. You might have one called HeatingRequired. Perhaps it reads a single DS18B20 to decide whether it's too cold. But alternatively, there may be a whole array of them in the house and one outside. Time of day may be a factor, peak electricity rates too, and the weather forecast. Once the function is written though, you do not care about any of this (until there's a bug).

The trouble is though, that function likely needs some data to help it make its decision. You can make the state data static, and indeed all the data about what the required temperature is by day and hour. But eventually, some other piece of code is going to want access to that data too and now you're in a bit of difficulty. It's going to have to be global, which exposes it to the entire codebase, or perhaps one .cpp file.

And that's how the bug appeared, because when your buddies came over for monthly poker night last week and complained that it was too warm (after the third beer) you went in and hacked it (after the third beer) to set the temperature lower on Thursdays and now the family keep complaining that it's cold and you can't see why because you put that 'fix' in some obscure function because you were in a hurry.

Classes let you overcome this. You can arrange it so that the data can be shared by class member functions but no-one else can see it. If that data was private you would have had to hack the class itself for your poker buddies and next Thursday when people complain, the search space for the bug is much reduced.

In large projects, private defends your objects from abuse by other developers. In Arduino projects, they generally defend you from yourself :wink:

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.