Pages

Friday, November 24, 2017

Easy tutorial for C / C ++ - class 2 (class)

Easy tutorial for C / C ++ - class 2 (class)

- Let's create a simple class.

Example Code

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

class tClass{
   private :
     int Na;
     int Nb;

   public :
     void init();
     void input(int,int);
     void prn();
};

void tClass::init(){
    Na = 10;
    Nb = 20;
}

void tClass::input(int A, int B){
    Na = A;
    Nb = B;
}

void tClass::prn(){
     cout << " Na = " << Na << ", Nb = " << Nb << endl ;
}

int main() {

     tClass x;

     x.init();
     x.prn();

     x.input(30,40);
     x.prn();

     return 0;
}

- We declared a class named 'tClass'. You have created the member variables (Na and Nb) and specified the access specifier as private.

* If you do not specify an access specifier, the default value 'private' is applied. 

- If you write 'private' (or public or protected), 'private' (or public or protected) will be applied to all subsequent members until another specifier appears.

- The members specified as 'private' are only available within the member functions of the class. Typically, member variables of classes are set to 'private'.

- Member functions (init (), input (), prn ()) are set to 'public'. If it is set to 'public', it can be used in member functions in the class, and it can be used in the area where the object is declared. In general, you should set member functions to 'public'.

- We defined the member function 'init ()' of class 'tClass'. Since the member function is a member of the class, the scope operator (: :) is used to indicate membership. And the initial value is assigned to the member variable 'Na, Nb'.

- The member function 'input ()' is a function that allows you to assign a value to a member variable. The member function 'prn ()' of the 'tClass' class is a function that prints the value of the member variable.

- We defined object (class variable) 'x' in main function. We then used the member reference operator ('.') to access the member function and print the result. The result is as follows.

results :

 Na = 10, Nb = 20
 Na = 30, Nb = 40

- The first result is the initial value assigned to the member variable 'Na, Nb'. The second shows the result of changing the value assigned to the member variable 'Na, Nb' using the input method.

- If an attempt is made to change the value of a member variable directly in the main function (x.Na = 0;), an error occurs. This is because the member variable is set to 'private'. If you want to access member variables directly (without using member functions) in the main function, you can specify the access specifier as 'public'.

No comments:

Post a Comment