Friday, 31 May 2013

Constructors and destructors in C++


Constructor
l  A constructor is a member function of a class.
l  It is a special member function of a class whose name is same as the name of class.
l  It has no return type.
l  Constructors do not call explicitly.
l  It is invoked implicitly when an object of class is created.
l  An implicit constructor is generated by compiler whenever we do not write any constructor in class definition. This implicit constructor would be called during object creation.
l  If we define a constructor in the class then there will be no implicit constructor created by class.
l  Constructor should always be defined in public as we create objects outside the class definition. Although there are scenarios where we would like to define constructor in private.
l  Constructor solves the problem of initialization. We can initialize variables of primitive data type during creation of variable but this feature is optional.

For example: int x=3; //creation of variable x and initialize it with a value 3
Let us assume complex is a user defined data type.
complex c1=4; //error this is called problem of initialization during creation of object


l  This problem can be solved with constructor. Following example illustrates this in detail:
#include<iostream.h>
class complex
{
     private:
     int a,b;
     public:
     complex(int x) { a=x; b=x; }
     void getdata();
     void showdata();  
};
void complex:: getdata()
{
     cout<<”Enter two numbers”;
     cin>>a>>b;
}
void complex:: showdata()
{
     cout<<”a=”<<a<<”b=”<<b;
}
void main()
{
  complex c1=3;  //constructor is called
  c1.show();
}

l  Here, constructor is called when object c1 is created in main() function
l  Notice that a value 3 is assigned to c1. This notation is resolved as; during creation of object c1 constructor is called and 3 is passed as an argument, which is then received by variable x in constructor. Value of x is copied into a and b. Hence, member variables of object c1 are initialized during object creation.
l  Please note the following declarations
complex c1(3);
complex c1=complex(3);

l  These two notations and the one which is used in function main()(complex c1=3;} are all same. You can choose the one that you like the most.
l  What happens if we remain class specification same and change the code of function main().
New definition of main(). For class definition please refer above example:
void main()
{
  complex c1=3;
  complex c2;  //error: no proper match for the constructor in class complex
 …
}


l  Why this error occurs? Answer is simple there is only one constructor in class complex which takes one argument of type int. So the first line is valid. In the second line we are creating an object with no arguments for constructor. Also note that there is no implicit constructor created by compiler as compiler do such only when we do not define any constructor in the class.
l  To remove this error we should define another constructor in the class which takes no argument.
l  Now consider another example which is remarkable modification in the previous example
#include<iostream.h>
class complex
{
     private:
     int a,b;
     public:
     complex() { } //default constructor, constructor with no argument
            complex(int x)
{ a=x; b=x; } //parameterized constructor, one argument
     complex (int x, int y)
{ a=x; b=y; } //parameterize constructor for two arguments
            void getdata();
     void showdata();  
};
void complex:: getdata()
{
     cout<<”Enter two numbers”;
     cin>>a>>b;
}
void complex:: showdata()
{
     cout<<”a=”<<a<<”b=”<<b;
}
void main()
{
  complex c1=3;  //constructor with one argument is called
     complex c2(3,4); //constructor with two arguments is called
     complex c3; //default constructor is called
     c1.show();
  c2.show();
  c3.show();
}

l  Here, three versions of constructors are defined in the class complex.
l  Compiler will resolve the version of constructor by examine argument list. This mechanism is called constructor overloading. Since this happens during compilation it is known as compile time polymorphism.

Copy Constructor

l  Whenever an object is created and initialize by the object of same class, no need to define another constructor as bitwise copy of existing object is assigned to newly created object. But whenever you desire to change this traditional mechanism of bitwise copying, you can create a copy constructor.
l  Following example illustrates copy constructor:

#include<iostream.h>
class complex
{
     private:
     int a,b;
     public:
     complex() { } //default constructor, constructor with no argument
            complex(int x)
{ a=x; b=x; } //parameterized constructor for one argument
            complex (int x, int y)
{ a=x; b=y; } //parameterize constructor for two arguments
            complex (complex &c) //copy constructor
{   
   a= c.b;   
   b= c.a;
}
void getdata();
     void showdata();  
};
void complex:: getdata()
{
     cout<<”Enter two numbers”;
     cin>>a>>b;
}
void complex:: showdata()
{
     cout<<”a=”<<a<<”b=”<<b;
}
void main()
{
  complex c1=3;  //constructor with one argument is called
     complex c2(3,4); //constructor with two arguments is called
     complex c3; //default constructor is called
     complex c4=c2;  //copy constructor is called
     c1.show();
  c2.show();
  c3.show();
  c4.show();
}

l  Here, copy constructor is called during creation of object c4. We are passing reference of c2. Thus c is reference object in copy constructor.
l  Remember always to pass reference in copy constructor and not pass value of object otherwise it yields an error message. It is due to avoid recursive call of copy constructor.

Destructor

l  Destructor is also a member function of class.
l  The name of destructor is same as the name of class but preceded with a tilde (~) sign.
l  It has no return type.
l  It never takes any argument and hence can not be overloaded.
l  Destructor invokes automatically for an object, when object goes out of scope.
l  Destructor is called when object is destroyed. Whatever we code in destructor will run during object destruction.
l  Sometimes it is needed to perform some actions when an object is destroyed. For example, an object that allocates memory when it is created will want to free that memory when it is destroyed.
l  The following example illustrates the use of destructor.
#include<iostream.h>
class complex
{
     private:
            int a,b;
     public:
            complex() { } //default constructor, constructor with no argument
            complex(int x) { a=x; b=x; } //parameterized constructor for one argument
            complex (int x, int y) { a=x; b=y; } //parameterize constructor for two arguments
            complex (complex &c) //copy constructor
{          
   a= c.b;   
   b= c.a;
}
~complex()
{ cout<<”You are in destructor”; }
void getdata();
            void showdata();        
};
void complex:: getdata()
{
            cout<<”Enter two numbers”;
            cin>>a>>b;
}
void complex:: showdata()
{
            cout<<”a=”<<a<<”b=”<<b;
}
void main()
{
  complex c1=3;  //constructor with one argument is called
  complex c2(3,4); //constructor with two arguments is called
  complex c3; //default constructor is called
  complex c4=c2;  //copy constructor is called
  c1.show();
  c2.show();
  c3.show();
  c4.show();
}

l  We have added one more function in the previous program that is destructor.
l  You can see name of destructor is same as the name of the class preceded by a symbol called tilde (~).
l  This function is called every time when object goes out of scope.

Static Member variable and static member function
Members of a class can be qualified as static by using keyword static. Members those are static are different in behavior from other non static members of the class.
Life of the static members extends the entire run of the program.

Static member variable

l  When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class.
l  Static member variables need to be defined outside the class.
l  Static member variables are not associated with any object and thus also known as class variable.
l  Although object can access public static member variables of the class using dot (.) operator but that doesn’t mean that static member variable is associated with that object.
l  Static member variable can also be accessed with class name and scope resolution operator.
l  Memory allocation of static member variable doesn’t depend on creation of object of class.
l  Static member variables can be accessed through any of class member function, no matter if they are static or not.
l  Life time of static members extends the entire program.

Example of static member variables

#include<iostream.h>

class  marksheet
{
  private:
          int sub1,sub2,sub3,sub4,sub5;
          float per;
          int result; 
  public:
          static int displaycount;
            void getmarks()
            {
                        cout<<”Enter marks of five subjects:”;
                        cin>>sub1>>sub2>>sub3>>sub4>>sub5;
                        result=result_generation();
                        per=percentage();
            }
            int result_generation()
            {
                        if(sub1>=35&&sub2>=35&&sub3>=35&&sub4>=35&&sub5>=35)
                                    return(1);
                        return(0);
            }
            float percentage()
{
            int sum=sub1+sub2+sub3+sub4+sub5;
                        return(sum/5.0);
            }
            void show_result()
{
            cout<<”Subject 1: “<<sub1<<endl;
            cout<<”Subject 2: “<<sub2<<endl;
            cout<<”Subject 3: “<<sub3<<endl;
            cout<<”Subject 4: “<<sub4<<endl;
            cout<<”Subject 5: “<<sub5<<endl;
            cout<<”Result: ”;
            result==1? cout<<”PASS” : cout<<”FAIL”;
            cout<<”\nPercentage: “;
            result==1?cout<<per:;
            displaycount++;
            cout<<”Display No: “<<displaycount;
      }
};
int marksheet:: displaycount;
void main()
{
            marksheet m1,m2,m3;
            m1.getmarks();
            m1.showresult();
            m2.getmarks();
            m2.showresult();
            m3.getmarks();
            m3.showresult();
}

Try above program and see result
You will observe every time showresult() increments displaycount. No matter who calls showresult, there is only one copy of displaycount used by showresult().

In the above program, displaycount is a static member variable. Please go the points written above this program.


Static member function

l  Static member functions can access only static members of the same class.
l  Static member function can be called by class name and scope resolution operator.
l  Static member functions can also be accessed through object name and dot (.) operator, but that doesn’t mean that the static member function could access non static member variables of object.
l  You might have a surprised, why we use static member function while we can access static member variables from non static member function. Answer is simple, we can not call non static member functions from out side the class without using object and dot (.) operator. But we know that existence of static member variable does not depend on creation of object. So how we can access static member variables (private) from outside the class when none of the object is created? It can be accessed through static member functions.
l  Since static member functions are not associated with any particular object they can never access object’s non static variables. Although we can create an object of same class in static member function and can access object’s member from there.
l   

Example
#include<iostream.h>

class  marksheet
{
  private:
          int sub1,sub2,sub3,sub4,sub5;
          float per;
          int result; 
          static int displaycount;
  public:
            void getmarks()
            {
                        cout<<”Enter marks of five subjects:”;
                        cin>>sub1>>sub2>>sub3>>sub4>>sub5;
                        result=result_generation();
                        per=percentage();
            }
            int result_generation()
            {
                        if(sub1>=35&&sub2>=35&&sub3>=35&&sub4>=35&&sub5>=35)
                                    return(1);
                        return(0);
            }
            float percentage()
{
            int sum=sub1+sub2+sub3+sub4+sub5;
                        return(sum/5.0);
            }
            static int counter()
            {
                        displaycount++;
                        return(displaycount);
            }
            void show_result()
{
            cout<<”Subject 1: “<<sub1<<endl;
            cout<<”Subject 2: “<<sub2<<endl;
            cout<<”Subject 3: “<<sub3<<endl;
            cout<<”Subject 4: “<<sub4<<endl;
            cout<<”Subject 5: “<<sub5<<endl;
            cout<<”Result: ”;
            result==1? cout<<”PASS” : cout<<”FAIL”;
            cout<<”\nPercentage: “;
            result==1?cout<<per:;
      }
};
int marksheet:: displaycount;
void main()
{
            marksheet::counter();
            marksheet m1,m2,m3;
            m1.getmarks();
            m1.showresult();
            m1.counter();
            m2.getmarks();
            m2.showresult();
            m2.counter();
            m3.getmarks();
            m3.showresult();
            m3.counter();
}

Wednesday, 29 May 2013

Classes and Objects


Class
l  A class is usually represents a noun.
l  It encapsulates the state and behavior of the concept it represents.
l  It encapsulates the state through data placeholders called attributes(or member variables)
l  It encapsulates behavior through sections of code called methods (functions).
Object
l  Object is an instance of class.
l  Object is a runtime entity
l  Object is a physical representation of a class

An example of class

#include<iostream.h>
class distance
{
     private:
     int km,m,cm;
     public:
     void getdata()
     {
          cout<<”Enter KM, M, CM:”;
          cin>>km>>m>>cm;
     }
     void showdata()
     {
          cout<<”KM=”<<km<<”M=”<<m<<” CM=”<<cm;
     }
};
void main()
{
  distance d1,d2;
  d1.getdata();
  d2.getdata();
  d1.show();
  d2.show();
}

Access Specifiers

l  There are three access specifiers: private, protected and public.
l  These access specifiers are used to categorize access rules for class members
l  Those data members and member functions declared as private, can not accessed outside the class.
l  Those data members and member functions declared as public can accessed outside the class along with inside access
l  Protected works similar to private that is can not access from outside the class but the difference between private and protected will get clear in inheritance.

Properties of member functions
l  Member variables and member functions can be accessed from outside class with the help of object of the same class and dot operator, only when members are public.
l  Member functions can access other members of the same class regardless of their access category.
l  Member functions can access other members without using object and dot operator. For example, in above program getdata() is accessing km,m and cm without using object and dot operator. These variables are members of object who invoked member function getdata().
l  Member function can be defined inside or outside the class. If they are defined inside the class, mechanism is very clear from the above example, as we defined two member functions getdata() and showdata() inside the class.
l  When we intend to define member functions outside the class, we have to declare it inside the class. When we define member function outside, membership label should be placed between return type and function name. So the syntax is

return type Class name :: Function name (argument list)
{
… …...
}
l  All functions defined inside the class are inline by default. If definition of member function is written outside the class then inline keyword must use to make function inline.
l  Several different classes can use the same function name. The membership label will resolve their scope.

Function call by passing objects and returning objects

#include<iostream.h>
class complex
{
     private:
     int a;
     int b;
     public:
     void getdata();
     void showdata();
     complex add(complex);  
};
void complex:: getdata()
{
     cout<<”Enter two numbers”;
     cin>>a>>b;
}
void complex:: showdata()
{
     cout<<”a=”<<a<<”b=”<<b;
}
complex complex :: add(complex c)
{
  complex temp;
  temp.a=a+c.a;
  temp.b=b+c.b;
  return(temp);
}
void main()
{
  complex c1,c2,c3;
  c1.getdata();
  c2.getdata();
  c3=c1.add(c2);
  c3.show();
}

l  We have created three objects of type complex
l  We call getdata() twice first via c1 and then via c2.
l  Now member function add() is called via c1 and passes object c2 as a parameter.
l  In function add() value of c2 is received in object c.
l  We have created another object temp in function add() to temporary hold sum of c1 and c2.
l  Function add() returns object temp, this value is then get collected in object c3.
l  Show() function is next used to display content of c3. 

Thursday, 23 May 2013

Introduction of OOPs and Revision of basics


History of programming approaches
l  At each critical point in the evolution of programming, a new approach was created to help the programmer handle increasingly complex programs.
l  The first programs were created by toggling switches on the front panel of the computer.
l  This approach is suitable for only the  smallest programs
l  Next, assembly language was invented, which allowed longer programs to be written. 
l  The next advance happened in the 1950s when the first high level language (FORTRAN) was invented.
l  By using high level programming language, a programmer was able to write programs that were several thousand lines long. However the method of programming was ‘anything’ goes approach. It yields unreadable and unmanageable code.
l  Next invention is structured programming languages in the 1960s
l  C is a structured programming language as it contains control structures, code blocks and absence of goto (or at least minimal use)
l  To allow more complex programs to be written, a new approach of programming is needed. So the object oriented programming was invented.
l  OOP takes the best of the ideas embodied in structured programming and combines them with powerful new concepts that allow you to organize your program more effectively.

Inventions of programming languages
l  In 1940s, Assembly language was invented which is a machine level language; also it comes under low level language.
l  In 1950s, FORTRAN was invented. It is first high level programming language that is machine independent language.
l  In 1966, BCPL was invented by Martin Richards. BCPL stands for Basic Combined Programming Language.
l  In 1969, B language was developed by Ken Thompson. He is also know as developer of UNIX operating system.
l  In 1972, C language was developed by Dennis Ritchie at AT &T’s Bell Lab, New Jersy USA.
l  In 1979, C++ language was developed by Bjarne Stroustrup. Initially C++ was pronounced as C with classes.

Some Points about C++
l  C++ was developed by Bjarne stroustrup in the year 1979 at AT and T’s Bell Labs, New Jersey USA.
l  C++ is an enhancement in C, so it consists of all the features that C provides.
l  Initially C++ was known as ‘C with classes’.
l  In the year 1983, it is named as C++.
l  C++ is also a middle level language just like C.

Differences between C and C++

1) When a function takes no parameter, its prototype has the word void inside parenthesis.
int fun(void);
However, in C++ the void is optional.
int fun();
If this convention would use in C, it mean that nothing is said about the parameters.

2) In a C++ program, all functions must be prototyped. In C, prototypes are recommended but technically optional.

3) About keyword return:
In C++, if a function is declared as returning a value, that is return type other than void, any return statement within that function must contain a value.
In C, a non void function is not required to actually return a value. If it doesn’t, a garbage value is returned.

4) Comments:
In C, comments in the program can be specified by /*….*/
In C++, due to backward compatibility, /*….*/ is still used for multiple line comments. We can also make a single line as comment by prefix that line by //

5) Declaration of local variables
In C local variables can be declared only at the start of a block prior to any action statements.
In C++ local variables can be declared anywhere in the block.

6) Reference variable
In C++, reference variable are implicit pointers that acts as another variable name for some existing variable. There is no concept of reference variable in C.

7) Top Down and Bottom up approach
C programmer follows top down approach for programming
It is a program design technique that starts with the highest level of an idea and works its way down to the lowest level of detail.
C++ programmer adopts bottom up approach for programming.
In a bottom-up approach the individual base elements of the system are first specified in great detail. These elements are then linked together to form larger subsystems, which then in turn are linked, sometimes in many levels, until a complete top-level system is formed.

8) Procedure oriented Programming and Object Oriented Programming
Procedure oriented Programming
Main program is divided into small parts depending on the functions.
The Different part of the program connects with each other by parameter passing. Most of the functions use global data.
Object Oriented Programming
Main program is divided into small objects depending on the problem.
Data & functions of each individual object act like a single unit.
Each object controls its own data.
Data hiding is possible in OOP which prevent illegal access of function from outside of it. This is one of the best advantages of OOP
Input/Output Instruction
In C, standard input device is keyboard and scanf() is use to receive data from keyboard.
Also, standard output device is monitor and printf() is use to send data/message to monitor.
In C++, printf() can be replaced by ‘cout’:
l  cout<<”Hello ”;
l  This statement introduces two new C++ features, cout and <<.
l  cout is a predefined object.
l  The operator << is called the insertion or put to operator
l  It is used to display message on the screen.
Examples:
printf(“Hello ”);
cout<<“Hello ”;

printf(“sum of %d and %d is %d”, a, b, c);
cout<<“sum of ”<<a<<“ and “<<b<<“ is “<<c;

printf(“%d”,a+b);
cout<<a+b;

In C++, scanf() can be replaced by ‘cin’:
l  cin>>x;
l  cin>>y>>z;
l  The identifier cin is a predefined object in C++
l  The operator >> is known as extraction or get from operator
l  It is used to take input from keyboard.
Examples:
scanf(“%d”, &a);
cin>>a;
scanf(“%d%d”, &a, &b);
cin>>a>>b;

scanf(“%d%f”, &a, &c);
cin>>a>>c;

About header file iostream.h
We need to include header file iostream.h, as it contains declarations for the identifier cout and the operator <<.  Also it contains declarations for the identifier cin and operator >>.

Sample Program
#include<iostream.h>
void main()
{
            int x, s;
            cout<<”Enter a number”;
            cin>>x;
            s=x*x;
            cout<<”Square of “<<x<<” is “<<s;
}

Functions in C++


About main function
l  In C++, default return type of main function is int.
l  In C++, if a main function is not prefixed by any return type then it is assumed as int. In such cases if you do not return any int value by using keyword return, a warning occurs during compilation- “Function should return a value”. This situation can be avoided by using return keyword in main or use void before main.
Function Prototype
l  The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and type of return values.
 Its syntax is
      return type function name (argument list);

l  Function prototype is also known as function declaration.
l  If a function is declared outside any function that is globally, then function can be called from any part of the program.
l  If a function is declared inside a particular function, then it is called local declaration. This means function can be only called from the function where it is declared.

Function Call by Value
l  A function call by passing values
l  The called function creates a new set of variables and copies the values of arguments into them.
l  This mechanism is good if the function does not need to alter the values of the original variables in the calling program.

#include<iostream.h>   //header file contains declaration of cout and cin
int area(int,int);             // function declaration/prototype
void main()
{
  int l, b, a;
  cout<<“Enter length and breadth”;
  cin>>l>>b;
  a=area( l , b);              //function area() is called by passing two int values
  cout<<“Area of rectangle is “<<a;
}
int area(int L, int B)      //function definition
{
 return(L*B);
}

l  Here function area() is called by passing two int values, that is mentioned by writing variable names separated by comma in parenthesis.
l  Values of l and b are copied into variables L and B respectively.
l  Function can only access its own variables, therefore function area() cannot access l and b. This is the reason we copy value of l and b in L and B.
l  Function area() returns a value produced by product of L and B. This value is then stored in variable ‘a’ of function main().

Function call by passing address
l  There may some scenarios where we would like to change the values of variables in the calling program.
l  Addresses can always be stored in special variables called pointers.

#include<iostream.h>
main()
{
 int a,b;
 void swap(int *, int *);
 cout<<“Enter two numbers: “;
 cin>>a>>b;
 swap(&a,&b);
 cout<<“a=“<<a<<” b=“<<b;
}
void swap(int *p, int *q)
{
 int t;
 t=*p;
 *p=*q;
*q=t;
}

l  Above program is of swapping the contents of two variables ‘a’ and ‘b’.
l  Notice the function call swap(&a, &b), here we pass addresses of variables ‘a’ and ‘b’ in place of values as we want to make changes possible in variable ‘a’ and ‘b’ from function swap().
l  These addresses get collected in pointers p and q.
l  swap () function returns nothing as it can directly makes changes in variables a and b using pointers p and q.

Function call by reference
l  A reference is implicit pointers that for all intents and purpose act like another name for a variable.
l  C++ permits us to pass parameters to the functions by reference.
l  The formal arguments in the called function become aliases (alternative name) to the actual arguments.
#include<iostream.h>
void main()
{
 int a,b;
 void swap(int &, int &);
 cout<<“Enter two numbers: “;
 cin>>a>>b;
 swap(a,b);
 cout<<“a=“<<a<<” b=“<<b;
}
 void swap(int &x, int &y)
{
 int t;
 t=x;
 x=y;
 y=t;
}

l  Here, function swap() is called by passing references of variable ‘a’ and ‘b’.
l  x and y are reference variables that is another names of ‘a’ and ‘b’ respectively
l  So we do not create extra copies of ‘a’ and ‘b’. 

Inline function
l  Function in a program is to save memory space which becomes appreciable when a function is likely to be called many times.
l  However every time a function is called, it takes lot of extra time in executing a series of instructions for tasks such as jumping to the functions, saving registers, pushing arguments into the stack and returning to the calling function.
l  So when function is small it is worthless to spend so much extra time in such tasks in cost of saving comparatively small space.
l  To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.
l  An inline function is a function that is expanded in line when it is invoked.
l  Compiler replaces the function call with the corresponding function code.
l  inline is a request not a command.
l  The benefit of speed of inline functions reduces as the function grows in size.
l  So the compiler may ignore the request in some situations.
Few of them:
·        Function containing loops, switch, goto.
·        Functions with recursion
·        Containing static variable.

#include<iostream.h>
inline int add(int, int);
void main()
{
  int a,b;
  cout<<”Enter two numbers”;
  cin>>a>>b;
  int sum=add(a, b);
  cout<<”Sum is “<<sum;
}
int add(int x, int y)
{  return(x+y); }


Default arguments

l  C++ allows us to call a function without specifying all its arguments. In such case function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared.
#include<iostream.h>
int add(int,int,int z=0);
void main()
{
  int a,b,c;
  cout<<”Enter three numbers”;
  cin>>a>>b>>c;
  int s3=add(a,b,c);
  cout<<s3;
  int s2=add(a,b);
  cout<<s2;
}
int add(int x,int y,int z)
{
  return(x+y+z);
}

l  The default value is specified in a manner syntactically similar to a variable initialization. The above prototype declares a default value of 0 to the argument z.
l  Here, we have only one version of function add, which is capable of taking three arguments as well as two arguments.
l  When function add() has two parameters, then first value is received in x, second value is received in y and there is no value for z but z is by default containing 0.

Function overloading

l  Overloading refers to the use of same thing for different purposes. Function overloading means, we can use the same function name to create functions that perform a variety of different tasks. This is called function polymorphism or compile-time polymorphism in OOP. Another is run time polymorphism which we’ll discuss later
l  The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type (return type).

#include<iostream.h>-
float area(int);
int area(int,int);
void main()
{
  int  r;
  cout<<”Enter radius of a circle”;
  cin>>r;
  float a=area(r);    
  cout<<”Area of circle is “<<a;
  int l,b,A;
  cout<<”Enter length and breadth of rectangle”;
  cin>>l>>b;
  A=area(l,b);
  cout<<”Area of rectangle is “<<A;
}
float area(int R)
{ return(3.14*R*R); }
int area(int L, int B)
{ return(L*B); }

Structure in C++


Structure in C
l  Structure is a collection of dissimilar elements.
l  Structure is a way to group variables.
l  Structure is way to create user defined data type

sruct book
{
  int id;
  float price;
  char title[20];
};

l  Here, book is a user defined data type.
l  In above example, structure book is a group of three variables id, price and title.
l  We can easily understand that these variables are of different type.
l  Do not forget to put semicolon at the end of structure body.
l  Till the structure is only defined and not actually used to create variables, no space is allocated for these variables.
l  When defining structure, mentioning variables in structure body is not actually creating variables (hence no memory consumed), instead we are just defining a memory model for those variables that could be created using data type book.

Creating structure variables

sruct book
{
  int id;
  float price;
  char title[20];
};

main()
{
  struct book b1,b2;
  …
  …
}

l  Here, we declare two variables of type book.
l  Each variable b1 and b2 will consume 26 bytes of memory space (i.e. sum of the memory consumed by member variables)
l  In C, keyword struct should always be prefixed during each use of such user defined data type.

Accessing members of structure

sruct book
{
  int id;
  float price;
  char title[20];
};
main()
{
  struct book b1,b2;
  printf(“Enter id, price and title of book”);
  scanf(“%d%f”,&b1.id, &b1.price);
  gets(&b1.title[0]);
  b2=b1;
  …
  …
}

l  Variables b1 and b2 both are of type book consuming 26 bytes each, containing three variables: id, price, title.
l  Members cannot be accessed freely, it should always be prefixed with variable of book type and dot( . ) operator.
l  We can copy the contents of b1 in b2, as shown in the above example. This helps an easy access to group of variables. No need of copying each and every element one by one.

Differences between structures of C and C++

l  In C++ a structure can have both variables and functions as members. In C a structure can have only variables as members.
l  In C++ members can be private, protected or public but in C there is no facility of access specifiers (Private, protected and public are access specifiers and we will discuss them in the next segment).
l  In C++, a structure can have inheritance. On the other hand in C a structure does not support inheritance.
l  In C++, the struct keyword can be omitted in the declaration of structure variables, but in C, the struct keyword is mandatory during the use of structure defined data-type.
Example:
#include<iostream.h>
struct complex
{
     private:
     int a;
     int b;
     public:
     void getdata()
     {
          cout<<”Enter two numbers”;
          cin>>a>>b;
     }
     void showdata()
     {
          cout<<”a=”<<a<<”b=”<<b;
     }
};
void main()
{
  complex c1,c2;
  c1.getdata();
  c2.getdata();
  c1.show();
  c2.show();
}


l  In C++, structure may contain functions along with variables as members.
l  Here, we defined four members; two are member variables (a and b) and two are member functions (getdata() and showdata())
l  Notice that we define member variables with access specifier private. Also, member functions with access specifier public.
l  Those members are private, cannot be accessed from outside the structure body.
l  Those members are public, can be accessed from outside the structure.
l  We can define structure in C++ exactly in the same way as we do in C. This is due to support backward compatibility.
l  If we do not mention any access specifier for members of structure, then it is assumed public.

Class and Structure in C++ are similar

l  Just replace the keyword struct with keyword class.

#include<iostream.h>
class complex
{
     private:
     int a;
     int b;
     public:
     void getdata()
     {
          cout<<”Enter two numbers”;
          cin>>a>>b;
     }
     void showdata()
     {
          cout<<”a=”<<a<<”b=”<<b;
     }
};
void main()
{
  complex c1,c2;
  c1.getdata();
  c2.getdata();
  c1.show();
  c2.show();
}

l  You can very well understand that the definition style and accessing methods of class members are exactly same as we did in structure example.
l  The only difference between class and structure in C++ is that by default the members of a class are private; on the other hand, by default the members of a structure are public.
l  A class is a way to bind the data and its associated functions together. (encapsulation)
l  In C++, class and structure both allows the data and functions to be hidden, if necessary, from the external use. (data hiding)
l  In C++, when defining a class or structure, we are creating a new abstract data type that can be treated like any other built in data type.

A common question arises why concept of class exist when structure fulfill all the requirements. The strong reason concerns maintaining upward compatibility from C. In C++, a C-style structure is also perfectly acceptable in a C++ program. Since in C all structure members are public by default, this convention is also maintained in C++. Further because class is syntactically separate entity from struct, the definition of a class is free to evolve in a way that will not be compatible with a C like structure definition. Since the two are separated, the future direction of C++ is not restricted by compatibility concerns.