V
V
vvafree2017-10-26 11:19:09
Programming
vvafree, 2017-10-26 11:19:09

Likbez. Variables for C++ classes?

Good afternoon. Such a situation, is it possible to store variables used in one class without initializing them outside the class?
For example:

int a;

Class n1;
n1.func1(a);
n1.func2(a);

Is it possible to initialize a variable a inside a class (but not inside some class method)? Outside of this class, the variable will not be used.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2017-10-26
@vvafree

Yes, you can. In this case, such a variable will be called a class property .

Example
class Students {
    // Имя студента
    std::string name;
    // Фамилия
    std::string last_name;
    // Пять промежуточных оценок студента
    int scores[5];
    // Итоговая оценка за семестр
    float average_ball;
};

Link

V
Vladimir A, 2017-11-08
@hauptling

Variables in a class can be public, private or protected. In your case, I advise you to use private ones and set them through the constructor or set methods. and to pull out through the get methods.
For example:

#include <iostream>

class rabbit
{
public:
     rabbit(int value)
     {
          m_value = value;
     }
     void SetValue(int value)
     {
          m_value = value;
     }
     int GetValue()
     {
          return m_value;
     }
private:
     int m_value;
     
};

int main()
{
     rabbit mrRabbit(10);
     std::cout << mrRabbit.GetValue();
     
     mrRabbit.SetValue(100);
     std::cout << mrRabbit.GetValue();
     
     return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question