Class is a user-defined data type, it holds its data members as well as member functions that could be accessed and used by creating an instance of that class.
The classes are an intrinsic feature of C++ that constitutes Object-Oriented programming.
The variables inside a defined class are called data members while the functions are called member functions.
Any Class name must begin with an uppercase letter. If a class name is made of more than one word, then the first letter of each word must be in uppercase. Example
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
Classes contain data members and member functions, however the access of these data members and variable depends on the access specifiers used.
Member functions of a class can be defined inside the class definition or outside the class definition.
The classes in C++ are similar to structures in C but differ only by; the class defaults to private access control, and the structure defaults to public.
All features of Object-Oriented Programming revolve around classes in C++ including Abstraction, Inheritance, Encapsulation, and so on. However, the Objects of the class hold separate copies of data members. During programming, one can create as many objects of a class as needed.
Objects:
Every object has its unique data variables.
Objects are instances of a class, that holds the data variables declared within a class, and the member functions work on these class objects.
Objects are initialized using special class functions known as Constructors. This will be discussed in detail in subsequent tutorials.
Additionally, if an object is out of its scope, a special class member function called Destructor is called to release the memory reserved by the object. The C++ language does not have an Automatic Garbage Collector just like JAVA, however, the Destructor in C++ performs this task.
Box Box1; // Declare Box1 the first object of class Box;
Box Box2; // Declare Box2 the second object of class Box;
Example:
#include <iostream>
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
void main( )
{
Box Box1; // Declare Box1 object of class Box
Box Box2; // Declare Box2 object of class Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 5.0;
Box1.breadth = 3.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 5.0;
Box2.breadth = 3.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
getch();
}