Members of the class type have property called access level which determines who can access them. In C++ there are three access levels: public, private, and protected.
Based the access level, compiler checks if the access to the member is permitted, otherwise it generates compilation error.
Structs have public as default access level for members whereas classes have private as default access level. And thus, classes are not aggregator as they posses opposite properties from an aggregate.
Setting access levels
Structs and classes have default levels for their members. However, we can explicitly specify the access levels using access specifiers. C++ provides us three access specifiers: public:, private:, and protected:.
For example,
#include <iostream>
class Point
{
private:
int x{};
int y{};
public:
void print() const
{
std::cout << x << ", " << y << "\n";
}
};
int main(int argc, char const *argv[])
{
const Point p{};
p.print();
return 0;
}x and y data members are private (which they are by default so explicit private: is redundant). print member function is public. A function member of any access level is able to access any data member of the classes.
Note
If we pass an argument to a member function of the same class, member function should be able to access the members of the object passed as the argument.