I'm new to C++, . The first thing I was wondering about when I started looking at C++ code is that classes have access specifiers such private, protected and public.
Compilation failed due to following error(s).
error: 'int MyClass::y' is private within this context
myObject.y = 50; // Not allowed (y is private)
^
sky.cpp:8:9: note: declared private here
int y;
^
sky.cpp:19:13: error: 'int MyClass::z' is protected within this context
myObject.z = 30; //
^
sky.cpp:10:9: note: declared protected here
int z;
^
I was just wondering, what exactly is the purpose of declaring private, protected and public.
Code:
#include <iostream>
using namespace std;
class MyClass {
public: // Public access specifier
int x;
private: // Private access specifier
int y;
protected; // Protected access specifier
int z;
};
int main() {
MyClass myObject;
myObject.x = 25; // (x is public)
myObject.y = 50; // (y is private)
myObject.z = 30; // (z is protected)
return 0;
}
error: 'int MyClass::y' is private within this context
myObject.y = 50; // Not allowed (y is private)
^
sky.cpp:8:9: note: declared private here
int y;
^
sky.cpp:19:13: error: 'int MyClass::z' is protected within this context
myObject.z = 30; //
^
sky.cpp:10:9: note: declared protected here
int z;
^
I was just wondering, what exactly is the purpose of declaring private, protected and public.