Classes/Objects
What is object oriented programming?
This consists of creating objects that contain data and functions. This is different from procedural programming that performs operations on data sequentially. Classes and objects are two main aspects of object oriented programming.
Example:
Class: Fruits
Objects: Apple, Mango, Cherry
Another aspect of this programming is attributes (e.g. Color and size) and methods (e.g. Break and speed) of various objects.
Create a Class
To create a class we use the keyword class.
In the following example the class keyword is used to create a class. Public is the access specifier (In detail later in this module). The variables declared within the class Num and Name_string are attributes. At last use of a semicolon is mandatory.
Example:
class Name_Class //The class
{
public //Acess specifier
int Num; //Attribute
string Name_string; //Attribute
};
Create a object
An object is created from a class
The syntax includes creating an object of Name_class specify the class name, followed by the object name.
We can access the class attributes using (.) on the object
Example:
#include <iostream>
#include <string>
using namespace std;
class Name_Class //The class
{
public: //Acess specifier
int Num; //Attribute
string Name_string; //Attribute
};
int main()
{
Name_Class my_Obj; // Create an object of Name_Class
// Access attributes and set values
my_Obj.Num = 16;
my_Obj.Name_string = "Demo Code";
// Print values
cout << my_Obj.Num << "\n";
cout << my_Obj.Name_string;
return 0;
}
Output:
16
Demo Code