Class - RJAE5/2143-OOP GitHub Wiki
Classes
The fundamental building block of object-oriented programming, especially in C++, is known as a Class. These customizable data types allow you to bundle primitive types as well as other user-defined types into one package via the concept of encapsulation. Additionally, classes contain functions that operate on the separate data items, these are known as methods.
A class makes use of access modifiers to accomplish data hiding or abstraction. Typically, all of the attributes and helper functions are held in the "private" or "protected" sections while methods are located in the "public" section to be access from anywhere in the program. In the most basic classes, these methods include constructors and destructors, setters (manipulating the data), and getters (returning the data).
Example
Classes can be used to describe general items that have a lot of features, especially if they are prone to changing. The following example depicts how a class might be used to describe a person.
class Person
{
private: // These are only accessible from within the class
string name;
int age;
char gender;
string SSN;
string occupation;
public: // These can be called from anywhere in the program
Person() // Default constructor
{
name = "John Doe";
age = 35;
gender = 'M';
SSN = "000-000-0000";
occupation = "Computer Scientist";
}
void setAge(int a) // Generic setter
{age = a;}
char getGender() // Generic getter
{return gender;}
};
Important Notes
- Instantiating a class by using the data type makes an object which will have it's own set of attributes attached with it.
- There are many types of classes, such as abstract, interfaces, and concrete classes
- Classes can inherit from other classes which allows derived classes to access methods and attributes from the base class
- The default access level of a class is
private, subsequently, beginning the main body of a class withprivate:is redundant.- This is contrary to a struct where the default access level is
public.
- This is contrary to a struct where the default access level is