Saturday, September 28, 2013

Classes and Structures in c++

Class : It is an encapsulated unit containing the blue print of data members and member functions of an entity or concept in the real world.

This is the entry point into the OOPS paradigm.

Syntax : 
                class class_name {
                
                access_modifier :
                                       //data members and member function declaration

                access_modifier :
                                       //data members and member function declaration
                };


access modifier : it is a way to mention who can access the data members and member functions.

Now let's take an example and try to understand what is actually a class.

Let's take the example of a human being. Now, let's take into consideration the various aspects and behaviours of a typical human being. 
The data members associated with a Human Being is :

1> Name
2> Height
3> Weight
4> Complexity 
and many many  more....
what are the basic functionalities of a typical human being.

1> eat()
2> sleep()
3> walk()
4> sit()
5> speak()
and many many more....

Now say you want to implement the concept of a human being in a c++ program. What will you do??? or What is the best possible way to do it???
The answer is a class....



class HumanBeing {
private:
 float weight, height;
 char name[40], complexity[20];
public:
 void eat() {
  cout << "Eating !!!";
 }
 void sleep() {
  cout << "Sleeping !!!";
 }
 void walk() {
  cout << "Walking !!!";
 }
 void sit() {
  cout << "Siting !!!";
 }
 void speak() {
  cout << "Speaking !!!";
 }
};


Now, this is the basic blue print of a person class in c++. Now, you may be not knowing several things in the above program. But don't worry we will learn them one by one.

At first
Let's learn some of the basic principals of OOPs :

1> Encapsulation : The process of binding of data members and member functions together into a single unit is known as Encapsulation.

In other the above definition is nothing but a fancy way of saying that a OOPs
language needs a class(or a similar concept). Since, we can see in the above code block that the unit HumanBeing has bounded in a single unit the data members(Height, Weight, Complexion) and member functions(eat(), sleep(), sit()) into a single unit. 

2> Abstraction(Data Hiding) : The process of hiding the unessential data members and revealing only what is required is known as Abstraction.

This is implemented in c++ with the help of access modifiers. If you look closely at the code above you will notice the use of the word private: before declaring the data members. This tell the c++ compiler that these data members can be accessed only by the member functions of the class it is contained in.

3> Message Passing : It is the phenomenon of instructing an object to do a particular task.

This is achieved in c++ with the help of method call.

Method : The functions associated with an object is known as Methods. 
                

For example, if you want and object of the class HumanBeing to sit than you have to instruct it to do the same using the method sit().

Object : It is an entity with existence that has characteristics and behaviours of it self. 

or

It is a instance of a class.

New Text Document.

Now, let's understand this more clearly
















The above picture is showing the fact that the space for the object  is allocated when we instantiate the object and nothing is done in memory when the definition of the class is encountered by the compiler. The memory is allocated when we declare an object of the class for the first time.


Constructors : It is a special type of a function(not exactly a function) that is called when an object space is allocated for an object. 
    
   Purpose(Intended) : It is used to initialize the data members of a class.
    
   Syntax Rules required for declaring a Constructor :
   
   1> They must not have any return type(not even void. They are
mean functions and do not want to return anything).

   2> They must have the same name as the class.

   3> It may or may not have  Parameters.

   4> They can be overloaded(Yes you thought right... just like function).

   5> They can have any access specifier(But most preferably public).

    
   Let's see a example to make things more clear.....

#include<iostream>
#include<string>
using namespace std;
class Test {
 // a class without a constructor....
public :
 //data members...
 int a;
 string s;
 float f; 
 long l;
};

class TestWithConstructor {
 // a class with a constructor....
public :
 int a;
 string s;
 float f;
 long l;
 TestWithConstructor() {
  a = 0; s = "Nothing"; f = 0.0f; l = 12l;
 }
};
int main() {
 // this creates an object of type class 'Test' named 'myTest'
 Test  myTest; 

 //printing the values of the data members of the class Test...
 cout << "\n\n  Data Memebers of class Test : \n  ";
 cout << myTest.a << " : " << myTest.s << " : " << myTest.f << " : " << myTest.l;

 // this creates an object of type class 'TestWithConstructor' named 'myTestWithConstructor'
 TestWithConstructor  myTestWithConstructor; 

 //printing the values of the data members of the class Test...
 cout << "\n\n  Data Memebers of class Test : \n  ";
 cout << myTestWithConstructor.a << " :  " << myTestWithConstructor.s << " : " << myTestWithConstructor.f << " : " << myTestWithConstructor.l;
 cout << "\n\n  ";
 system("pause");
}

Output :

Let's understand it a bit more :









































There are three points we learn from this :

1> If we do not create a constructor than the c++ compiler does the work for you.
2> The Default constructor does not initialize any thing for you.
3>   The first thing that c++ does after allocating memory for an object is to call the constructor of the class.
4> It may be used for other initialization tasks that are pivotal to the working of the class.

Missconception :  It is used to allocate memory for the object.

                          C++ Structure

The only difference between a c++ class and a c++ structure is that in a structure the members are public by default.



struct Example {
 int a, b, c;
 string s;
 Example() {
  s = "Nothing"; 
  a = b = c = 0; // a nice use of multiple chained assignment statements
 }
};

though not much apparent by the syntax but the difference will be apparent when we see exactly how they are used.



Now lets talk about the access modifiers a bit.


Public : It is used when you want the whole outside world to know about that field and allow them to access and mutate that field (if the field is not constant that is).

Protected : will not be clear until we reach inheritance.

Private : it is this access modifier that is responsible for the feature abstraction(hiding from the cruel and dangerous world what is unnecessary and not safe).


struct ExampleStructure {
 int a, b, c;
 string s;
 ExampleStructure() {
  s = "Nothing"; 
  a = b = c = 0; // a nice use of multiple chained assignment statements
 }
};
class ExampleClass {
 //follows the most general guidelines of OOPS
 int a, b, c;
public :
 ExampleClass() {
 }
 // inside class(or implicit) definition
 int get_a() { 
  return a;
 }
 int get_b() {
  return b;
 }
 int get_c() {
  return c;
 }

 // outside class(or explicit) definition
 void set_a(int a); 
 void set_b(int b); 
 void set_c(int c); 
};

void ExampleClass::set_a(int a) {
 this->a = a;
}
void ExampleClass::set_b(int b) {
 this->b = b;
}
void ExampleClass::set_c(int c) {
 this->c = c;
}
void main() {
 ExampleStructure myStructure;
 ExampleClass myClass;
 //accessing data field members
 cout << "\n\n accessing fields of structure : " << myStructure.a << " " << myStructure.b << " " << myStructure.c;
 cout << "\n\n accessing fields of class : " << myClass.get_a() << " " << myClass.get_b()<< " " << myClass.get_c();

 //mutating data field members
 myStructure.a = myStructure.b = myStructure.c = 1;
 myClass.set_a(1); myClass.set_b(1); myClass.set_c(1);
}


the above example is an overly simplified definition of  a structure and class 
in c++.

First lets look at the class definition :

setter and getter :  Ask any one who has some experience of writing code any OOPS language and they will tell you that setters and getters are inseparable part of your coding arsenal.

So, what are they actually  you ask??

They are just normal member functions of a class who are assigned the specific task of accessing a data member of a class and setting their values.
Nothing else.

Getter  gets the values of the data members of a class.
       eg : get_a, get_b, get_c
Setter  sets the values of the data members of a class.
       eg : set_a, set_b, set_c

Now lets talk about this(???). Confused, don't be, I mean to say lets talk about the keyword 'this'. For this we have to dig a bit into the working of the c++ language. Lets suppose that we have more than one objects of a particular class and say we call a member function using one of the objects.
Now ask yourself how will the c++ compiler know exactly which object is used to call the member function(now please don't say by looking at the syntax because while running, the program is a sequence of bytes and not the well formatted multi-coloured text that you see at in your IDEs). 

Well the answer is the 'this' pointer. When we call a method by using an object. The 'this' pointer is passed as the first argument to the function. Of course it is done implicitly by the compiler and you are not aware of it.

Following is an image of an object in memory :
































No comments:

Post a Comment