Friday, 23 September 2016

DESTRUCTORS


If a constructor is created in a program for initializing or giving values to the variables then it should also have a destructor to destroy the object. A destructor is used to destroy the objects that have been created by the constructor.
It is also a memeber function of the class with same name as class but is preceded by title('~'). 

Syntax: ~destructor-name()
                 { body }

NOTE: No matter how many constructors are there in a program, there will be only one destructor needed to destroy all the objects.


Why do we need Destructors?

During the construction of an object, resources may be allocated, that means memory is allocated to an object. Now before destroying an object we need to deallocate them. So destructor is used for clean-up tasks.




Example:

class Sample
{
int a;
int b;
~Sample(){cout<<"Destructing";} //Destructor

public: 
            Sample(){a=0; b=0;}
            void fun1();
            void fun2();
};

Now if the objects of class "Sample" are created in order then their objects are destroyed in reverse order. This is done by Destructor.


For Example: 

{
Sample s1;      //Object s1 created 
Sample s2;      //Object s2 created

//Object s2 destructed 
//Object s1 destructed 
}

The objects s1 and s2 were destroyed by the destructor "~Sample()".


For More Help:


Monday, 12 September 2016

COPY CONSTRUCTOR


Whenever you initialize an instance using values of instance of same type, the compiler will use the copy constructor. To put it in a simple way, a copy constructor used to initialize the the objects of its same type.It creates a reference object to it own class and uses their objects as it own parameters.

Syntax: class-name(class-name &object-name)




Example:

class A
{
                  int a;
                  int b;

public: 
                  A(int i,int j)    //parameterized constructor to initialize values
                  {
                     a=i;  
                     b=j;
                   }

                  A(A &obj)        //Copy constructor
                  {
                    cout<<"This is copy constructor\n";
                    a=obj.a;
                    b=obj.b;
                   }

                   void show()
                   {
                     cout<<"a= "<<a<<"\nb="<<b;
                   }
}; 

void main()
{
clrscr();

A obj1(2,3);  //Parameterized constructor called
A obj2(obj3);  //Copy constructor called

getch();
}

The above statement A obj2(obj3), copied the obj3 to obj2.


For More Help:



Sunday, 11 September 2016

PARAMETERIZED CONSTRUCTORS



It means constructors with the parameters. Different form the default constructors because default constructors have no parameters. You can have as many parameterized constructors that you want but it should have the different number or types of arguments. The compiler finds out which constructor to invoke by comparing the number or the type of arguments(just like we were having in function overloading). 

Syntax: constructor-name(parameters)
        {
         body of the constructor
        }


Example:

class student
{

private:      int roll_no;

public:       
              student(int r)          //Parameterized constructor
                  {
                      roll_no=r; 
                   } 
                   .
                   .
};

void main()
{
clrscr();

int a=10;
student s1(a);   //This will invoke the parameterized constructor of class 'student'

getch();
}

The above statement, when the object was created of class 'student' , it will pass the variable 'a' to the constructor 'student' and will initialize the roll_no variable.


For Help:


DEFAULT CONSTRUCTOR


A constructor that accepts no parameters is called default constructor.
Constructor with parameters is not considered as the default constructor. It is invoked as soon as object of the class is declared. Any class can have only one Default constructor.

Syntax: class-name object-name;

Even when we didn't declare a constructor in a class, the compiler automatically invokes a default constructors with no arguments.So, if a class has no explicit constructor the compiler supplies a default constructor. 


Example: 

class student
{
               int roll_no;
public: 
               void getdata(void);
               void showdata(void);
                .
                .   //Definitions
};
student s1;  /*The compiler uses default constructor with no arguments for creating object 's1'. Default constructor is no public member of the class */

void main()
{
s1.getdata();
s1.showdata();
}

For More Help:


Saturday, 10 September 2016

CONSTRUCTORS


A constructor is a member function of  a class that has the same name as that of the class. It is automatically called, when an object of the class is created. It's main use is to initialize the members of the class.


Why do we need Constructors?

 giving the default values cannot be done outside the class. Array can be initialized at the time of the declaration but class is different. It's private members are not accessible outside the class. So there is a need of constructors which can initialize the values to the variables if no values are given to them.

Example:


class A
{
private:
             int a;
             int b;
public:
            A()         //This is called Default Constructor
            {
               a=1;
               b=1;
            }
};

void main()
{
clrscr();
A obj;   //Object created 
getch();
}

As soon as the Object is created the private members 'a' and 'b' are initialized. This makes the initialization easy because earlier we have to declare another function for initializing but constructor made that easy.

PROTECTED MEMBERS OF CLASS 


Protected members are the members that can be used only by the member function and the friends of the class. Just like the private members they can be accessed by non-member functions.
The difference comes when we talk about inheritance. protected members are inheritable but private members are non-inheritable.

SCOPE

Protected members of a class have class scope that means these can only be accessed by the member functions of the class. 

Example:

class A
{
private:
         int a;
         void test()
         {
           cout<<a;
         }

protected:   int b;

public: 
         int i;
         void show()
         {
           cout<<i+5;
           a=9;     //This is valid because the private memebr can be used by the member functions of that class
           test(); //Valid. Just like the variable, member function can also be accessed by the public members of that class 
         }
};
A obj;  //object created

void main()
{
clrscr();
obj.show();  //Valid
obj.i= 20;   //Valid
obj.a=40;    //Invalid. a is private 
obj.test();  //Invalid
obj.b=7;     //Invalid. b is protected
getch();
}

ARRAY OF OBJECTS


When you define a class, you can also define the array of objects of Class type. Declared after the class definition is over and is defined like the other arrays are defined.


Example: 

class student
{
private: 
             int roll_no;
            

public:
             void getdata(int roll)
             {
               roll_no= roll;
         
             }
            
            void show()
            {
              cout<<"Roll No.: "<<roll_no;
            
            }
};

student s[5];    //Array of Objects of "student" Class Type which contain the information of 5 Students

void main()
{
clrscr();
int rollno;


for(int i=0; i<5;i++)
  {
    cout<<"Enter the Details of Student "<<i+1<<"\n";
    cin>>rollno;   
    
    s[i].getdata(rollno);
  }

for(int j=0;j<5;j++)
 {
   cout<<"\nStudent "<<j+1<<"\n";
   s[j].show();
 }
getch();
}


Now let's say, to invoke function 'show' the 3rd Object of class student, we will write: 
s[2].show();  // As array starts from 0

Friday, 9 September 2016

REFERENCING CLASS MEMBERS


You can't use the member functions of the class directly outside the class. To make use of a Class Specified, we create Objects of type Class.

Syntax: class_name obj1, obj2,...; 
Example: Student s1, s2;
This will create two objects s1, s2 of Student Class type.This will become more clear with the help  of an example.


Example: 

class student
{
        private:
                     int roll_no;
                     char name[20];

        //Private members are only accessible through the member functions of that class

          public: 
                        void take_data()          //For taking values
                        {
                           cin>>roll_no;
                           gets(name);
                        }
                       
                        void show()          //For showing values
                        {
                           cin<<roll_no;
                           cout<<"\n"<<name;
                        }
} ;
student s1, s2;   // This will create objects s1, s2 of Student class type. We can use them anywhere in the program according to our needs.

Only the public Members are called by non-member functions using the Objects.
Syntax: object_name.function_name(actual arguments);

Now to call the function 'take_data' from class student, statement will be:
     s1.take_data();
or s2.take_data();

and for function 'show':  s1.show(); or s2.show();

For more Help: 

Wednesday, 7 September 2016

CLASS DEFINITION 


Member functions of a class can be defined in two place:
1. Inside the class Definition
2. Outside the class Definition


Inside the Class Definition

Just like we define functions, Same goes goes in case of defining the Classes i.e. you can define them before without giving the Prototype. Just start the Class Definition just like You stats a Function Definition.

Example: 
class Student
{
private:
                 int roll_no;
                 char name[20];

public:
                  void accept()
                  {
                    cout<<"Enter Roll No: "; cin>>roll_no;
                    cout<<"Enter Name: ";  gets(name);      //For accepting the char string
                   }

                  void show()
                  {
                    cout<<"\nDetails:\n";
                    cout<<"Roll No: "<<roll_no;
                    cout<<"\nName: "<<name;
                  }
}


Outside the Class Definition

Defining the function Sometimes becomes Bulky when your Programs become Complicated or when it is too large. So Many Programmers gives the Class Definition outside the Class.

Syntax:  return-type class_name::function_name(parameter list)
              {
              }
:: is a Scope resolution operator which specifies the  scope of the Function which is inside the Class.

Example: 
                   void Student::show()
                   {
                     cout<<"\nDetails:\n";
                     cout<<"Roll No: "<<roll_no;
                     cout<<"\nName: "<<name;
                    }
where 'Student' is our Class and 'show' is the function with Return type 'void'.

To Know more about Classes and their Definitions: 


Tuesday, 6 September 2016

CLASSES


Class is a simple combining of the variables and functions into a Single Unit. 

Consider a Student. His characteristics will be Roll Number, Name, Class(I mean Standard), etc. He will have some functions like Reading Writing and Playing. Combing all the characteristics and functions into a single Unit will form a 'CLASS'.

First starts with a keyword 'class'. with a class_name and the Braces will Contain  the entities and the associated Functions with it. Semicolon at the End.

Example: 

class Student
{
int roll_no;
char name[20];

void show()
 {
       cout<<"Roll No: "<< roll_no;
       cout<<"\nName: "<<name;
  }
};

The above example contains variables roll_no, char string name and function 'show'. All are combined in a Single Unit. This implements Abstraction and Encapsulation. 

Class has three members: private, public and protected

Private: which we don't want anyone to inherit and don't want to show to the Outside World. Variables and Functions declared in this section are protected from the Direct Outside Access. If no Label is specified then by Default, members are Private.

Public: it's Members can be Accessed form Outside the Class.


Protected: It's members are accessed inside the Class and also from the class who inherit them. 

NOTE: Friend class can access the private and protected members of the other Class.


For Help:



Sunday, 4 September 2016

DEFAULT ARGUMENTS


In Function Overloading the compiler executes a function by Comparing the Type and Number of Arguments. 

For Example:  


int hello(int a=10, float b=5.2, char c='v')
{
.
.
.
}

Now, Calling the Function in Main.

cout<<hello(20, 6.3);
This statement will run the 'hello' Function and  will invoke the Values 20,6.3, v respectively.

cout<<hello(30);
This statement will run the 'hello' function and will invoke the Arguments Values 30,5.2,v respectively. 

Just Like the above Example if the Values of the Function's Arguments is not specified in the Main during the Calling then it Uses the Default Values given to it. 

Tuesday, 30 August 2016

FUNCTION OVERLOADING


We can create as many functions as we want but what will happen if they belong to the same class category, Let's say that there are two function printing some values but of different types.In this case we will be needing two functions. But we can make the functions with the same name but the condition is with the different number of Parameters or arguments. 
It will be more clear with the help of the program.

PROGRAM: 

#include<iostream.h>
#includ<conio.h>

void show(int a)      //Function 1
{
cout<<"This function contains Integer value = "<<a;
}


void show(float b)    //Function 2
{
cout<<"This function contains Float value = "<<b;
}

void main()
{
clrscr();

// Now we will Call the functions
show(2.3);      
show(10);
getch();
}  


OUTPUT:

This function contains Float value = 2.3
This function contains Integer value = 10

Now the first calling was 'show(2.3)'. This was a float value, so the compiler compared both the functions and their Return types and Parameters. When it found the float value, the function 2 was called then. Then the next call 'show(10)' was having an Integer value, so comparing with the parameters it executed the First Function. 

Also :


Saturday, 27 August 2016

Functions


Functions are the small parts or we can say sub-parts of the program that perform special tasks. They can be reused again when required.

Syntax: type function-name(parameters)

              {body of the function }

type means it's return type and if the function is not returning any value then its void. For Example if the function is returning an integer value then 'type'= 'int'. If no type is specified then Compiler assumes an integer value by default. So it is good to specify the Return type. Then in the parentheses is parameter_list. It can be leaved blank but it's up to the programmer whether he wants variables or not.



Program: 

#include<iostream,.h>
#include<conio.h>
void main()
{
clrscr();
void show();
{
 cout<<"Hello World";
}
getch();
}

Output:  Hello World

This will create a function 'show' inside the main. When the program will execute the compiler will go inside the function 'show' and will display the statement "Hello World" and will come out of the function and the program will terminate.

Function Prototype is the declaration of the function that tells the return type and the number of arguments and type of arguments that are going to be used in the program. If the function's definition is written first then there is no need for function prototype because function's definition is declaration itself( i.e. prototype of the function).


A function can be invoked in two manners:

1. Call by Value
2. Call by Reference


Call by Value

Call by value means calling the function by the matching of the number of arguments. The Call by Value copies the value of actual parameters(These are the parameters that appear in the function call statement or you can say in the 'main' function) into the formal parameters(These are in the function's definition). The function creates it's own copy of values and then uses it.


Program:

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
void show(int);
int num;
cout<<"Enter a Number: ";
cin>>num;
cout<<"Original Number: "<<num<<"\n";
show(num);
cout<<"Number after change: "<<num<<"\n";
getch();
}

void show(int num)
{
num= 5;
cout<<"Value of Number in function: "<<num<<"\n";
}


Output: 

Enter a Number: 10
Original Number: 10
Value of Number in function: 5
Number after change: 10

'show' function copies the value from the actual and shows it in formal. So by call be value does not changes the original values(i.e. actual parameters). So even after calling the function 'show' there will be no change in actual.

For Understanding Better: 


Array Initialization


It is a simple method to initialize an array, whether One-Dimensional or Two Dimensional.
The values given in the brackets is separated by the comma. All the elements in the list will have the same base type because as you know an array consists of elements of  same type of elements whether float, int,etc.




Syntax: type array_name[size]={values_list};


Example:

int num[6]={23,56,12,81,10,1};
Now the values would be assigned like:
num[0] =23;
num[1] =56;
num[2] =12;
num[3] =81;
num[4] =10;
num[5] =1;

Two Dimensional arrays are also initialized in the same manner.

Syntax: type array_name[size][size]={values_list};


Example:

int matrix[3][3]={1,2,3,4,5,6,7,8,9};
Now the values would be assigned like:
matrix[0][0]=1;
matrix[0][1]=2;
matrix[0][2]=3;
matrix[1][0]=4;
matrix[1[1]=5;
matrix[1][2]=6;
matrix[2][0]=7;
matrix[2][1]=8;
matrix[2][2]=9;

It can be also be written as
int matrix[3][3]= { 1,2,3,
                               4,5,6,
                               7,8,9 };

C++ also allows you to skip the size of the array in initialization statement. The main advantage of not declaring the size is that we can increase or decrease the value_list without changing dimensions.

Example:      int square[]={2,3,4,5};

                     char name[]="User";