Friday, February 18, 2011

Classes and objects and Methods and properties


**************Classes and objects and Methods and properties**********
 
A class is a user defined data type like a structure or a union. 
A class consists of data variables and functions. 
These variables and functions are called members of the class. 
The variables are called data members and functions are called member functions. 
The member functions are also called methods. 
The data members are called properties of the class. 
An object is the instance of the class. 
An object is like a compound variable of the user defined type.
It links both code and data. Within the object, members of the class can be public or private to  the object. 
The declaration of a class is syntactically same as structure. The class is declared using keyword class.
The general form of the declaration of the class is:-

class class_name
{
          

            access_specifier:

                        data members

            access_specifier:

                        data functions

 

} object_list;

*****Why Use a Class****
Once a class has been created the programmer can:
1) create multiple instances of a class 
2) reuse classes in more than one program

****Access Specifiers***
1) Private members of a class are accessible only from within other members of the same class or from their friends. 
2) Protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. 
3) Public members are accessible from anywhere where the object is visible. 


**************Example:1******************
#include<iostream.h>
#include<conio.h>
class emp
{
 Private:                       //Access Specifier
 char name[20];
 int roll;
 char dept[8];

 public:
 void getdata()
 {
  cout<<"Enter the RollNo:";
  cin>>roll;
  cout<<"\n Enter the Name:";
  cin>>name;
  cout<<"\n Enter the Dept:";
  cin>>dept;
 }
 void display()
 {
  cout<<"\nRollNo="<<roll;
  cout<<"\n Name="<<name;
  cout<<"\n Dept="<<dept;
 }
};
void main()
{
 emp e;             //object creation
 e.getdata();
 e.display();
 getche();
}
 
*****Example 2***********
#include<iostream.h>
#include<conio.h>
class cube
{

                    public:

                        double side;

                        double volume()

                        {

                                    return(side*side*side);

                        }

};

void main()

{

            cube c1,c2;

            cout << "Enter the lenght of the cube" << endl;

            cin >> c1.side;

            cout << "The volume of the cube is : " << c1.volume() << endl;

            c2.side=c1.side +2;

            cout << "The volume of the second cube is : " << c2.volume() << endl;
}

*****scope operator*******
The scope operator (::) specifies the class to which the member
being declared belongs, granting exactly the same scope properties 
as if this function definition was directly included within the class definition.


// classes example
#include <iostream.h>
#include<conio.h>

class CRectangle
 {
    int x, y;
  public:
    void set_values (int,int);
    int area ()
    {
     return (x*y);
    }
};

void CRectangle::set_values (int a, int b)
 {
  x = a;
  y = b;
}

void main () 
{
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
 
}

*******Multiple Objects Creation******
// example: one class, two objects
#include <iostream.h>
#include<conio.h>

class CRectangle 
{
    int x, y;
   public:
    void set_values (int,int);
    int area ()
   {
      return (x*y);
   }
};

void CRectangle::set_values (int a, int b) 
{
  x = a;
  y = b;
}
void main () 
{
  CRectangle rect, rectb;
  rect.set_values (3,4);
  rectb.set_values (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
}

-----------Constructors------------------
Constructors in C++ are special member functions of a class. They have the same name as the Class Name. 
There can be any number of overloaded constructors inside a class, provided they have a different set of parameters. There are some important qualities for a constructor to be noted. 
1) Constructors have the same name as the class. 
2) Constructors do not return any values 
3) Constructors are invoked first when a class is initialized. Any initializations for the class members, memory          allocations are done at the constructor.

-----------Destructors-------------------
Destructors in C++ also have the same name, except for the fact that they are preceded by a '~' operator. 
The destructors are called when the object of a class goes out of scope. It is not necessary to declare a constructor or a destructor inside a class.
If not declared, the compiler will automatically create a default one for each.

-----Examples---------
#include<iostream.h>
#include<conio.h>

class Student
{
 private:
 int Sub1,Sub2,Sub3,Total;
 float avg;
 public:
 Student()                      //Default Constructor
 {
  cout<<"Enter the Marks For Three Subjects";
  cin>>Sub1>>Sub2>>Sub3;
  Total=Sub1+Sub2+Sub3;
  avg=Total/3;
 }
 void put()
 {
  cout<<"Total Marks Of Student is"<<Total<<endl;
  Cout<<"Avg Marks Of Student is"<<avg<<endl;
 }
 ~Student()
 {};
};
void main()
{
 Student s;
 s.put();
 getche();
}

----------Parameterized Constructor---------
#include <iostream.h>
#include<conio.h>

class CRectangle
 {
    private:
    int width, height;

    public:
    CRectangle (int,int); //Parameterized Constructor
    int area ()
   {
        return (width*height);
   }
   ~CRectangle()
     {};
};
CRectangle::CRectangle (int a, int b)
 {
  width = a;
  height = b;
}

void main ()
 {
  CRectangle rect (3,4);
  cout << "rect area: " << rect.area() << endl;
  getche();  
}

-------Overloading Constructors----
Like any other function, a constructor can also be overloaded with more than one function that have the same name but different types or number of parameters. 
Remember that for overloaded functions the compiler will call the one whose parameters match the arguments used in the function call.
In the case of constructors, which are automatically called when an object is created, the one executed is the one that matches the arguments passed on the object declaration.

-----Example------
// overloading class constructors
#include <iostream.h>
#include <conio.h>

class CRectangle
 {
    int width, height;
    public:
    CRectangle ();
    CRectangle (int,int);
    int area (void) 
   {
       return (width*height);
   }
};

CRectangle::CRectangle ()
 {
  width = 5;
  height = 5;
}

CRectangle::CRectangle (int a, int b) 
{
  width = a;
  height = b;
}

void main () 
{
  CRectangle rect (3,4);
  CRectangle rectb;
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  getche();
}

-------------Copy Constructor----------
A copy constructor is a special constructor in the C++ programming language used to create a new object 
as a copy of an existing object. 
The first argument of such a constructor is a reference to an object of the same type as is being constructed.
Copying of objects is achieved by the use of a copy constructor and a copy assignment operator.

----------Example---------------
#include<iostream.h>
#include<conio.h>
class A
{
 int a;
 public:
 A()         //default Constructor
 {}
 A(int x)  //Parameterized Constructor
 {
  a=x;
 }
 A(const A &x)       //Copy Constructor
 {
  a=x.a;
 }
 void display()      
 {
  cout<<"A::"<<a<<endl;
  
 }
};
void main()
{
 A obj1(10);
 A obj2(obj1);
 A obj3=obj1;
 
 obj1.display();
 obj2.display();
 obj3.display();
 getche();
}
-----Inline Function-----
Inline functions are functions where the call is made to inline functions.
The actual code then gets placed in the calling program.

---Reason for the need of Inline Function---
Normally, a function call transfers the control from the calling program to the function and after the execution of the program returns the control back to the calling program after the function call.
These concepts of function saved program space and memory space are used because the function is stored only in one place and is only executed when it is called. 
This concept of function execution may be time consuming since the registers and other processes must be saved before the function gets called. 
If the function is short, the programmer may wish to place the code of the function in the calling program in order for it to be executed. 
This type of function is best handled by the inline function.

---What happens when an inline function is written?----
The inline function takes the format as a normal function but when it is compiled it is compiled as inline code. 
The function is placed separately as inline function, thus adding readability to the source program.
When the program is compiled, the code present in function body is replaced in the place of function call.

----The general format of inline function is as follows:---

                                   inline datatype function_name(arguments) 

The keyword inline specified in the above example, designates the function as inline function.
For example, if a programmer wishes to have a function named exforsys with return value as integer 
and with no arguments as inline it is written as follows: 

                                  inline int exforsys( ) 

Example: 
#include <iostream.h>
#include<conio.h>
inline int exforsys(int x1)
{
return 5*x1;
} 
void main( )
{
int x;
cout << “\n Enter the Input Value: ”;
cin>>x;
//The exforsys(x) gets replaced with code return 5*x1;
//Call is made to the function exforsys
cout<<”\n The Output is: “ << exforsys(x);
getche();
} 


------Creating Array Objects---------
Example:
#include<iostream.h>
#include<conio.h>

class Student
{
 private:
 int Sub1,Sub2,Sub3,Total;
 float avg;
 public:
 void get()
 {
  cout<<"Enter the Marks For Three Subjects";
  cin>>Sub1>>Sub2>>Sub3;
  Total=Sub1+Sub2+Sub3;
  avg=Total/3;
 }
 void put()
 {
  cout<<"Total Marks Of Student is"<<Total<<endl;
  Cout<<"Avg Marks Of Student is"<<avg<<endl;
 }
 
};
void main()
{
 Student s[3];
 clrscr();
 for(int i=0;i<3;i++)
 {
       s[i].get();
 } 
 for(int i=0;i<3;i++)
 {
       s[i].put();
 }
 getche();
}

--------What is a Friend Function?---------------------------

A friend function is used for accessing the non-public members of a class. 
A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class.

----------------Some important points to note while using friend functions in C++:--------

The keyword friend is placed only in the function declaration of the friend function and not in the function definition.

It is possible to declare a function as friend in any number of classes.

When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend.

A friend function, even though it is not a member function, would have the rights to access the private members of the class.

It is possible to declare the friend function as either private or public.

The function can be invoked without the use of an object. 
The friend function has its argument as objects.

----Example----
#include<iostream.h>
#include<conio.h>
class exforsys
{
               private:
                        int a,b;
               public:
               void test()
               {
                      a=100;
                      b=200;
               }
friend int compute(exforsys e1) //Friend Function Declaration with keyword friend and 
                                                     //with the object of class exforsys to which it is friend
       passed to it
};
int compute(exforsys e1)
{
                                                    //Friend Function Definition which has access to private data
return int(e1.a+e1.b)-5;
}

void main()
{
exforsys e;
clrscr();
e.test();
cout<<"The result is:"<<compute(e);
//Calling of Friend Function with object as argument.
}
---------------Operator overLoading-----------




-------------------------------------------
-Binary operator overloading example-
-------------------------------------------
#include<iostream.h>
#include<conio.h>
class complex
{
  float x,y;
 public:
 complex(){}
 complex(float r,float i)
 {
  x=r;
  y=i;
 }
 complex operator+(complex);
 void display()
 {
  cout<<x<<"+"<<y<<"i"<<endl;
 }
};
complex complex::operator+(complex c)
{
 complex temp;
 temp.x=x+c.x;
 temp.y=y+c.y;
 return(temp);
}
void main()
{
 complex c1,c2,c3;
 c1=complex(10,20);
 c2=complex(3,54);
 c3=c1+c2;
 clrscr();
 cout<<" ";c1.display();
 cout<<"+ ";c2.display();
 cout<<"-----------"<<endl;
 cout<<" ";c3.display();
 getch();
}


-------------------------------------------
-Unary operator overloading example-
-------------------------------------------
#include<iostream.h>
#include<conio.h>
 class space
 {
  int x;
  int y;
  int z;
  public:
  void getdata(int a,int b,int c);
  void display();
  void operator-();
 };
  void space::getdata(int a,int b,int c)
  {
  x=a;y=b;z=c;
  }
  void space::display()
  {
  cout<<"x="<<x<<", y="<<y<<", z="<<z;
  }
  void space::operator-()
  {
  x=-x;
  y=-y;
  z=-z;
}
void main()
{
 space s;
 s.getdata(10,-20,30);
 clrscr();
 cout<<"\ncoordinate of a point in space:\n";
 s.display();
 -s;
 cout<<"\ncoordinate of a point in space of mirror image:\n";
 s.display();
 getch();
}

----------------------------------------------------------------
--Introduction To Inheritance----
----------------------------------------------------------------
What is Inheritance? 
Inheritance is the process by which new classes called derived classes are created from existing classes called base classes.
The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class.

For example, a programmer can create a base class named fruit and define derived classes as mango, orange, banana, etc. 
Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additional attributes 
or features specific to these newly created derived classes. 
Mango would have its own defined features, orange would have its own defined features, banana would have its own defined features, etc. 


Features or Advantages of Inheritance: 

Reusability: 

Inheritance helps the code to be reused in many situations.
The base class is defined and once it is compiled, it need not be reworked. 
Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed. 


Saves Time and Effort: 

The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed. 
Increases Program Structure which results in greater reliability.


General Format for implementing the concept of Inheritance: 

class derived_classname: access specifier baseclassname 

Example:
class sample: public exforsys

Types Of Inheritance
1) Single
2) Multiple
3) Multilevel

Example:Single Inheritance

#include<iostream.h>
#include<conio.h>
class base
{
 int a;
 public:
 void fungeta()
 {
  a=10;
 }
 void funputa()
 {
  cout<<"A::"<<a;
 }
};
class derived:public base
{
 int b;
 public:
 void fungetb()
 {
  fungeta();
  b=20;
 }
 void funputb()
 {
  funputa();
  cout<<"B::"<<b;
 }
};
void main()
{
 clrscr();
 derived d;
 d.fungetb();
 d.funputb();
 getche();
}

Example:Multilevel Inheritance

#include<iostream.h>
#include<conio.h>
class A
{
 int a;
 public:
 void fungeta()
 {
  a=10;
 }
 void funputa()
 {
  cout<<"A::"<<a;
 }
};
class B:public A
{
 int b;
 public:
 void fungetb()
 {
  fungeta();
  b=20;
 }
 void funputb()
 {
  funputa();
  cout<<"B::"<<b;
 }
};
class C:public B
{
 int c;
 public:
 void fungetc()
 {
  fungetb();
  c=30;
 }
 void funputc()
 {
  funputb();
  cout<<"C::"<<c;
 }
};
class D:public C
{
 int d;
 public:
 void fungetd()
 {
  fungetc();
  d=40;
 }
 void funputd()
 {
  funputc();
  cout<<"D::"<<d;
 }
};
void main()
{
 clrscr();
 d obj;
 obj.fungetd();
 obj.funputd();
 getche();
}

Example:Multiple Inheritance

#include<iostream.h>
#include<conio.h>
class A
{
 int a;
 public:
 void fungeta()
 {
  a=100;
 }
 void funputa()
 {
  cout<<"A::"<<a;
 }
};
class B
{
 int b;
 public:
 void fungetb()
 {
  b=200;
 }
 void funputb()
 {
  cout<<"B::"<<b;
 }
};
class C
{
 int c;
 public:
 void fungetc()
 {
  c=30;
 }
 void funputc()
 {
  cout<<"C::"<<c;
 }
};
class D:public A,public B,public c
{
 int d;
 public:
 void fungetd()
 {
  fungeta();
  fungetb();
  fungetc();
  d=40;
 }
 void funputd()
 {
  funputa();
  funputb();
  funputc();
  cout<<"D::"<<d;
 }
};
Void main()
{
 clrscr();
 D obj;
 obj.fungetd();
 obj.funputd();
 getche();
}












  
 


No comments:

Post a Comment