Can someone explain me how classes work in c++ ? I don't know why would i want to use them and how do they work :3 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can someone explain me how classes work in c++ ? I don't know why would i want to use them and how do they work :3

I don't understand classes

13th Nov 2016, 9:14 AM
Megmind
Megmind - avatar
2 Answers
+ 1
class allows to manage you the privacy of you data. example class MyMessage( private string mex; MyMessage(string m){ mex=m; } public string getMess(){ return mex; } } in this way, nobody can directly acces to your message and edit it. example in main int main(){ MyMessage mm("ciao"); //now mm.mex value is "ciao" mm.mex = "hello"; /* this is WRONG!!! at compiling time because you defined mex as private so it's impossible to use it directly. the only way you can use it is through public method. in this case we defined getMessage() as public, so you can invoke it. private member can only bè accessed by class method.*/ cout << mm.mex; //is WRONG too! cout << mm.getMessage(); // correct. so in your class you decide to set mess but you prevent to edit it. for editing it you can define another public method inside the class as: public void updateMex(string m){ mex = m; } in this case you can modify your mex through call that method inside main. another important thing is the possibilità to derive class from another. that allows to write code once and adding some staff later. For example class Person have name and surname. you can define class Student by recicling class Person code cause Student is a Person. and in this way you can extends class Person in student and adding some new member to it as exams or School.
13th Nov 2016, 9:54 AM
Matteo Tardelli
Matteo Tardelli - avatar
0
Thanks Matteo :D
13th Nov 2016, 1:13 PM
Megmind
Megmind - avatar