C++ TUTORIALS - C++ Classes & Objects
C++ Classes & Objects
ADVERTISEMENTS
Accessing the Data Members:
Concept | Description |
---|---|
Class member functions | A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. |
Class access modifiers | A class member can be defined as public, private or protected. By default members would be assumed as private. |
Constructor & destructor | A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted. |
C++ copy constructor | The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. |
C++ friend functions | A friend function is permitted full access to private and protected members of a class. |
C++ inline functions | With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function. |
The this pointer in C++ | Every object has a special pointer this which points to the object itself. |
Pointer to C++ classes | A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it. |
Static members of a class | Both data members and function members of a class can be declared as static. |
ADVERTISEMENTS
C++ Class Definitions:
class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };ADVERTISEMENTSDefine C++ Objects:
Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type BoxAccessing the Data Members:
#include <iostream> using namespace std; class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; // box 2 specification Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.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; return 0; }