Wednesday, 29 October 2014

Class declarations and usage in C++ with examples

Class declarations and usage in C++ with examples:

Classes are the user defined data types. The default specifier of the class is private.
A class is blue print of the data type. The memory is not allocated for the class till you declare the object for that.
The definition of the class is defined using the keyword “class” and enclosed with the {};, it should ends with the semicolon as shown above.

Members of the class
The variables which are defined in the class are called as members
Methods of the class
The functions inside the class is called as methods / member functions
Access specifiers
 The class will support three access specifiers “public, private, protected”, the default access specifier is “private”
 Constructor
A constructor is a special function in a class that is called when a new object of the class is created.
Destructors
A destructor is also a special function, which is called when created object is deleted.
The Copy Constructor
This is also a type of the constructor that is used to create a copy of an existing object of the same class type.
Friend functions
It is one of the key features in c++. Friend functions are used to access the private and protected data of class. When the complier found the keyword friend, it knows the given function is friend function, the complier automatically recognizes that the given function is a friend function.
Inline functions
 These are also functions, but the code is replaced at the compile time which reduces the function calling overhead.




Here is sample class holds the data
A 2D point class that holds two data variables x, y
This is the header file of the class, Good naming conventions for the variables and the functions will improve the program readability and easy understanding. My advice is making it as a habit.
class Point2D {

public:
  double m_dX, m_dY;
  // constructor of the class
  Point2D ();
    //Destructor of the class
  ~Point2D ();   
};
// Point2d.cpp file, which contains the definition for the functions
#include "Point2D.h"
// Initialize all the member variables of the class in the constructor
Point2D::Point2D () : m_dX (0.0), m_dY (0.0)
  { }
Point2D::~Point2D ()
  { }
#include "Point2D.h"
int _tmain (int argc, _TCHAR* argv[])
{ 
  /* instantiate the Point2D Class object */
  Point2D ocPoint;  // This is called as the default constructor
  ocPoint.m_dX = 20.0;
  ocPoint.m_dY = 10.0;
 return 0;
}


Example program that pass the class object as an argument to the function:

There are two types of arguments passing is possible
1.Pass by value

2. Pass by Reference


Now take the same class Point2D to understand the situation. i.e, how to pass the class object as an argument to the function.

1. The below is the example for the pass by value


#include <iostream>
using namespace std;
class Point2D                   
{
public:
 double m_dX, m_dY;
};
// Here the Func () accepts the Point2D object as an argumetnt, which is called as pass by value
void Func (Point2D ocPnt1, double dX, double dY)
{
 ocPnt1.m_dX += dX;
 ocPnt1.m_dY += dY;
}
int main ()
{
 Point2D ocPoint;
 ocPoint.m_dX = 1.0;
 ocPoint.m_dY = 2.0;
 Func (ocPoint, 10.0, 20.0);
  cout << "ocPoint(" << ocPoint.m_dX << "," << ocPoint.m_dY << ")" << endl;
 return 0;
}

In the above example, we are passing the copy of the class object to the function as an argument. In the above example the changes won’t effect the original data of the class

2. Example for Pass by Reference:

Passing the reference as an argument to the function is called as pass by reference.
We need to pass the class using a reference to the class so that the changes are reflected in the original, the below example will clarify all our doubts.
#include <iostream>
using namespace std;
class Point2D                   
{
public:
 double m_dX, m_dY;
};
// Here the Func () accepts the Point2D object as an argument, which is called as pass by reference
void Func (Point2D &ocPnt1, double dX, double dY)
{
 ocPnt1.m_dX += dX;
 ocPnt1.m_dY += dY;
}
int main ()
{
 Point2D ocPoint;
 ocPoint.m_dX = 1.0;
 ocPoint.m_dY = 2.0;
 Func (ocPoint, 10.0, 20.0);
      cout << "ocPoint(" << ocPoint.m_dX << "," << ocPoint.m_dY << ")" << endl;
 return 0;
}

Declaring the member functions of the class:

The functions are declared in the class are called as method/member functions.
The below example shows how to declare a me thon in the class
#include <iostream>

using namespace std;
class Point2D
{
public:
  double m_dX, m_dY;
 void Func (double dX, double dY)
 {
  m_dX = m_dX + dX;
  m_dY = m_dY + dY;
 }
 void Dump ()
 {
  cout << "m_dX = " <<  m_dX << "\t" << "m_dY = "<< m_dY << endl;
 }
};
int main()
{
   /* Create the object for the class */
  Point2D ocPnt;
  ocPnt.m_dX = 30.0;
  ocPnt.m_dY = 22.0;
   /* Create the second object */
  Point2D ocPnt1;
 ocPnt1.m_dX = 8.0;
 ocPnt1.m_dY = 5.0;
  /* call the member fucntion using two different objects */
  ocPnt.Func (2.0,  7.0);
 ocPnt1.Func (3.0, 1.0);
  /* Print the results */
 ocPnt.Dump ();
 ocPnt1.Dump ();
  getchar ();
 return 0;
} 

In the example, we made two functions as member functions (methods): offset() and print().


Initialization of a member variable in the constructor:

Manually initializing our fields of a class can get tedious. So, we need to initialize them when we create an instance. A method called when we are creating an instance is a constructor.
class Point2D

{
  double m_dX, m_dY;
public:
 Point2D ()
 {
  M_dX = 0.0;
  M_dY = 0.0;
 }
};

Parameterized Constructor:

The constructor accepts parameters, while creating the objects we can pass the inputs to that.
The below example contains two constructors, one is parameterized constructor and the other one is default constructor.
using namespace std;
using namespace System;
class Box
{
   public:
      Box () {} // default constructor
      // Constructor definition, parameterized constructor will accept the parameters
      Box(double l, double b, double h)      {
         cout <<"Constructor called." << endl;
         dlength = l;
         dbreadth = b;
         dheight = h;
      }
     /* volume function that classwill evaluate from the length, breadth and height */
      double Volume ()
      {
        return length * breadth * height;
      }
      int GetCnt () {
        return iCnt;
      }
   private:
      double dlength;     // Length of a box
      double dbreadth;    // Breadth of a box
      double dheight;     // Height of a box
};

Create the instances for the Box classes and pass the parameters as well.

#include "Box.h"
int _tmain (int argc, _TCHAR* argv[])
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2
   // Get the volume of the two boxes by calling the volume function
   cout << Box1.Volume () << Box2.Volume () << endl;
 getchar ();
 return 0;
} 

Pointers to Class:

The objects also be pointed to by pointers: Once declared, a class becomes a valid type, so it can be used as the type pointed to by a pointer. For example:
 
Box *pcBox1;

is a pointer to an object of class Box.

Similarly as with plain data structures, the members of an object can be accessed directly from a pointer by using the arrow operator (->). Here is an example with some possible combinations:
The below example program that helps the creation and the usage of the pointer to the class.
using namespace std;

using namespace System;
class Box
{
   public:
       int objectCount;
      int iCnt;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0) : iCnt (0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;iCnt++;
      }
      double Volume ()
      {
         return length * breadth * height;
      }
      int GetCnt () {
        return iCnt;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};
int _tmain (int argc, _TCHAR* argv[])
{
  Box ocBox1 (10, 90);
   Box *pcBox2, *pcBox3, *pcBox4;  // pointed by pcBox
  pcBox2 = &ocBox1; 
  pcBox3 = new Box (5, 6);
  pcBox4 = new Box[2] { {2,5}, {3,6} };
  cout << "Box1's Voilume: " << pcBox2->Volume () << '\n';
  cout << "*Box3's Volume: " << pcBox3->Volume () << '\n';
  cout << "*Box4's Volume: " << pcBox4->Volume () << '\n';
  cout << "Box4[0]'s Volume:" << pcBox4[0].Volume () << '\n';
  cout << "Box4[1]'s Volume:" << pcBox4[1].Volume () << '\n';     
  delete pcBox3;
  delete[] pcBox4;
 getchar ();
 return 0;
}  


The above expressions are read as
 
*pcBox is called as pointed to by pcBox
&ocBox1 is the address of ocBox1
pcBox4[0] is the first object pointed to by pcBox4
pcBox4[1] is the second object pointed to by pcBox4
pcBox4[n] is the (n+1)th object pointed to by pcBox4

The Destructor of the class:

The destructor is used to destroy the memory allocated for the class members when the object goes out of scope, and also it delete the pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.
Following example explains the concept of destructor:
using namespace std;

using namespace System;
class Box
{
   public:
       int objectCount;
      int iCnt;
      Box () { cout << "I am in the constructor of the class" << endl; }
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0) : iCnt (0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;iCnt++;
      }
      ~Box ()

      {
            cout << "I am in the destructor of the class" << endl;
      }
      double Volume ()
      {
         return length * breadth * height;
      }
      int GetCnt () {
        return iCnt;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};
int _tmain (int argc, _TCHAR* argv[])
{
  Box ocBox1 (10, 90);
   Box *pcBox2, *pcBox3, *pcBox4;  // pointed by pcBox
  pcBox2 = &ocBox1; 
  cout << "Box1's Voilume: " << pcBox2->Volume () << '\n';
 getchar ();
 return 0;
}
Compile the above code and execute it produces the following output:
Constructor called.

Box1's Volume: 1800
I am in the destructor of the class



No comments: