C + + class definition
Defining a class is essentially a blueprint for defining a data type. This does not actually define any data, but it defines what the name of the class means, that is, it defines what the object of the class includes, and what operations can be performed on that object.
The class definition begins with the keyword class followed by the name of the class. The body of the class is enclosed in a pair of curly braces. The class definition must follow a semicolon or a list of declarations. For example, we use the keyword class to define the Box data type, as follows:
class box{ public: double length; // the length of the box double breadth; // Width of the box double height; // the height of the box };
The keyword public determines the access properties of a class member. Within the scope of a class object, public members are accessible outside the class. You can also specify that the members of the class are private or protected, which we'll explain later.
Defining C + + objects
class provides a blueprint for an object, so basically an object is created from a class. Declares an object of a class, just like a variable that declares a primitive type. The following statement declares the two objects of a class Box:
Box Box1; // declaration Box1, type Box Box Box2; // declaration Box2, type Box
Both objects Box1 and Box2 have their own data members.
Accessing data members
The public data members of the object of the class can be accessed using the direct member access operator (.). To better understand these concepts, let's try the following example:
#include <iostream>#include<stdlib.h>using namespacestd;//instantiating an object of a classclassCoordinate//define a class{ Public://Access Qualifier intx; inty; voidPrintx () {cout<< x <<Endl; } voidPrinty () {cout<< y <<Endl; }};intMainvoid){ //Stack of wayscoordinate coor;//defines an object in the stackCoor.x =Ten;//accessing data members or member functionsCOOR.Y = -; Coor.printx (); Coor.printy (); //Heap The waycoordinate*p =Newcoordinate (); if(NULL = =p) {//failed to request memory return 0; } P->x = -;//accessing data members or member functionsP->y = $; P-Printx (); P-Printy (); DeleteP//Freeing Memoryp =NULL; System ("Pause"); return 0;}
It is important to note that private members and protected members cannot be accessed directly using the direct member access operator (.). We'll learn how to access private members and protected members in a follow-up tutorial.
C + + Class object definitions