Programming – Week 3

This week I’ve learned how to create classes using header and cpp files.

This is an example of a header named Student

 class Student
{
public:
 Student(std::string name, int age);

 int GetAge();
 void SetAge(int newAge);

 std::string GetName();
 void SetName(std::string newName);

private:
 int age;
 std::string name;
}; 

The keyword ”public” describes what functions and variables are accesable from outside the class. All ”private” variables and functions are only accesable inside the class.

Student(std::string name, int age)    is the constructor of the class. The constructor works like a function but is automaticly called when a object is initialized with the class name as datatype. In this case the constructor is overloaded, the default constructor does not have any parameters.

By having name and age private we can use functions such as SetAge and GetAge in order to controll the variables value.

Example:

void SetAge(int newAge)
{
    if (newAge >= 0)
    {
        age = newAge;
    }
}

Here i can say that we accept no age below 0.


Lämna en kommentar