Monday, October 20, 2014

Passing and Returning Object from Function in C++ Programming

Passing and Returning Object from Function in C++ Programming

In C++ programming, objects can be passed to function in similar way as variables and structures.

Procedure to Pass Object to Function

Passing Object to function in C++ Programming

Example to Pass Object to Function

C++ program to add two complex numbers by passing objects to function.

#include <iostream>
using namespace std;
class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void Read()
        {
           cout<<"Enter real and imaginary number respectively:"<<endl;
           cin>>real>>imag;
        }
        void Add(Complex comp1,Complex comp2)
        {
            real=comp1.real+comp2.real;
 /* Here, real represents the real data of object c3 because this function is called using code c3.add(c1,c2); */
            imag=comp1.imag+comp2.imag;
 /* Here, imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); */
        }
        void Display()
        {
            cout<<"Sum="<<real<<"+"<<imag<<"i";
        }
};
int main()
{
    Complex c1,c2,c3;
    c1.Read();
    c2.Read();
    c3.Add(c1,c2);
    c3.Display();
    return 0;
}
Output

Enter real and imaginary number respectively:
12
3
Enter real and imaginary number respectively:
2
6
Sum=14+9i

Returning Object from Function

The syntax and procedure to return object is similar to that of returning structure from function.
Returning Object from function in C++ Programming

Example to Return Object from Function

This program is the modification of above program displays exactly same output as above. But, in this program, object is return from function to perform this task.

#include <iostream>
using namespace std;
class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void Read()
        {
           cout<<"Enter real and imaginary number respectively:"<<endl;
           cin>>real>>imag;
        }
        Complex Add(Complex comp2)
        {
            Complex temp;
            temp.real=real+comp2.real;
/* Here, real represents the real data of object c1 because this function is called using code c1.Add(c2) */
            temp.imag=imag+comp2.imag;
/* Here, imag represents the imag data of object c1 because this function is called using code c1.Add(c2) */
            return temp;
        }
        void Display()
        {
            cout<<"Sum="<<real<<"+"<<imag<<"i";
        }
};
int main()
{
    Complex c1,c2,c3;
    c1.Read();
    c2.Read();
    c3=c1.Add(c2);
    c3.Display();
    return 0;
}

C++ Constructors

C++ Constructors

Constructors are the special type of member function that initialises the object automatically when it is created Compiler identifies that the given member function is a constructor by its name and return type. Constructor has same name as that of class and it does not have any return type.
..... ... .....   
class temporary
   {
       private: 
          int x;
          float y;
       public:
          temporary(): x(5), y(5.5)        /* Constructor  */
              {  
                     /* Body of constructor */
              }
          .... ...  ....
  }
  int main()
     {
        Temporary t1;
        .... ... ....
     }            
Working of Constructor
In the above pseudo code, temporary() is a constructor. When the object of class temporary is created, constructor is called and x is initialized to 5 and y is initialized to 5.5 automatically.
You can also initialise data member inside the constructor's function body as below. But, this method is not preferred.
temporary(){
   x=5;
   y=5.5;
}
/* This method is not preferred. /*

Use of Constructor in C++

Suppose you are working on 100's of objects and the default value of a data member is 0. Initialising all objects manually will be very tedious. Instead, you can define a constructor which initialises that data member to 0. Then all you have to do is define object and constructor will initialise object automatically. These types of situation arises frequently while handling array of objects. Also, if you want to execute some codes immediately after object is created, you can place that code inside the body of constructor.

Constructor Example

/*Source Code to demonstrate the working of constructor in C++ Programming */
/* This program calculates the area of a rectangle and  displays it. */ 
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2){ }   /* Constructor */
       void GetLength()
       {
           cout<<"Enter length and breadth respectively: ";
           cin>>length>>breadth;
       }
       int AreaCalculation() {  return (length*breadth);  }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp;
       }
};
int main()
{
    Area A1,A2;
    int temp;
    A1.GetLength();
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<endl<<"Default Area when value is not taken from user"<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}

Explanation
In this program, a class of name Area is created to calculate the area of a rectangle. There are two data members length and breadth. A constructor is defined which initialises length to 5 andbreadth to 2. And, we have three additional member functions GetLength(), AreaCalculation() and DisplayArea() to get length from user, calculate the area and display the area respectively.
When, objects A1 and A2 are created then, the length and breadth of both objects are initialized to 5 and 2 respectively because of the constructor. Then the member function GetLength() is invoked which takes the value of length and breadth from user for object A1. Then, the area for the objectA1 is calculated and stored in variable temp by calling AreaCalculation() function. And finally, the area of object A1 is displayed. For object A2, no data is asked from the user. So, the value of lengthwill be 5 and breadth will be 2. Then, the area for A2 is calculated and displayed which is 10.
Output
Enter length and breadth respectively: 6
7
Area: 42
Default Area when value is not taken from user
Area: 10

Constructor Overloading

Constructor can be overloaded in similar way as function overloading. Overloaded constructors have same name(name of the class) but different number of argument passed. Depending upon the number and type of argument passed, specific constructor is called. Since, constructor are called when object is created. Argument to the constructor also should be passed while creating object. Here is the modification of above program to demonstrate the working of overloaded constructors.
/* Source Code to demonstrate the working of overloaded constructors */
#include <iostream>
using namespace std;
class Area
{
    private:
       int length;
       int breadth;

    public:
       Area(): length(5), breadth(2){ }          // Constructor without no argument
       Area(int l, int b): length(l), breadth(b){ } // Constructor with two argument
       void GetLength()
       {
           cout<<"Enter length and breadth respectively: ";
           cin>>length>>breadth;
       }
       int AreaCalculation() {  return (length*breadth);  }
       void DisplayArea(int temp)
       {
           cout<<"Area: "<<temp<<endl;
       }
};
int main()
{
    Area A1,A2(2,1);
    int temp;
    cout<<"Default Area when no argument is passed."<<endl;
    temp=A1.AreaCalculation();
    A1.DisplayArea(temp);
    cout<<"Area when (2,1) is passed as argument."<<endl;
    temp=A2.AreaCalculation();
    A2.DisplayArea(temp);
    return 0;
}
Explanation of Overloaded Constructors
For object A1, no argument is passed. Thus, the constructor with no argument is invoked which initialises length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2 and 1 is passed as argument. Thus, the constructor with two argument is called which initialiseslength to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.
Output
Default Area when no argument is passed.
Area: 10
Area when (2,1) is passed as argument.
Area: 2

Default Copy Constructor

A object can be initialized with another object of same type. Let us suppose the above program. If you want to initialise a object A3 so that it contains same value as A2. Then, this can be performed as:
....
int main() {
   Area A1,A2(2,1);
   Area A3(A2);     /* Copies the content of A2 to A3 */
     OR, 
   Area A3=A2;      /* Copies the content of A2 to A3 */  
}
You might think, you may need some constructor to perform this task. But, no additional constructor is needed. It is because this constructor is already built into all classes.

C++ Programming Tutorial

C++ Programming Tutorial

C++ programming is on the one the most popular and widely used object-oriented programming language which was developed by Bjarne Stroustrup in 1979. C++ is derived from C programming. So, almost all code that run on C runs correctly on C++. If you have good understanding of basic features of C programming, you will have a head start learning C++.

C++ Class

A class is the collection of related data and function under a single name. A C++ program can have any number of classes. When related data and functions are kept under a class, it helps to visualize the complex problem efficiently and effectively.
Datas and function inside class in C++
A Class is a blueprint for objects
When a class is defined, no memory is allocated. You can imagine like a datatype.
int var;
The above code specifies var is a variable of type integer; int is used for specifying variable var is of integer type. Similarly, class are also just the specification for objects and object bears the property of that class.

Defining the Class in C++

Class is defined in C++ programming using keyword class followed by identifier(name of class). Body of class is defined inside curly brackets an terminated by semicolon at the end in similar way as structure.
class class_name
   {
   // some data
   // some functions
   };

Example of Class in C++

class temp
   {
      private:
         int data1;
         float data2;  
      public:  
         void func1()
           {   data1=2;  } 
        float func2(){ 
              data2=3.5;
              retrun data;
           }
   };
Explanation
As mentioned, definition of class starts with keyword class followed by name of class(temp) in this case. The body of that class is inside the curly brackets and terminated by semicolon at the end. There are two keywords: private and public mentioned inside the body of class.

Keywords: private and public

Keyword private makes data and functions private and keyword public makes data and functions public. Private data and functions are accessible inside that class only whereas, public data and functions are accessible both inside and outside the class. This feature in OOP is known as data hiding. If programmer mistakenly tries to access private data outside the class, compiler shows error which prevents the misuse of data. Generally, data are private and functions are public.

C++ Objects

When class is defined, only specification for the object is defined. Object has same relationship to class as variable has with the data type. Objects can be defined in similary way as structure is defined.

Syntax to Define Object in C++

class_name variable name;
For the above defined class temp, objects for that class can be defined as:
temp obj1,obj2;
Here, two objects(obj1 and obj2) of temp class are defined.

Data member and Member functions

The data within the class is known as data member. The function defined within the class is known as member function. These two technical terms are frequently used in explaining OOP. In the above class tempdata1 and data2 are data members and func1() and func2() are member functions.

Accessing Data Members and Member functions

Data members and member functions can be accessed in similar way the member of structure is accessed using member operator(.). For the class and object defined above, func1() for object obj2can be called using code:
obj2.func1();
Similary, the data member can be accessed as:
object_name.data_memeber;
Note: You cannot access the data member of the above class temp because both data members are private so it cannot be accessed outside that class.

Example to Explain Working of Object and Class in C++ Programming


/* Program to illustrate working of Objects and Class in C++ Programming */
#include <iostream>
using namespace std;
class temp
{
    private:
        int data1;
        float data2;
    public:
       void int_data(int d){
          data1=d;
          cout<<"Number: "<<data1;
         }
       float float_data(){
           cout<<"\nEnter data: ";
           cin>>data2;
           return data2;
         }
};
 int main(){
      temp obj1, obj2;
      obj1.int_data(12);
      cout<<"You entered "<<obj2.float_data();
      return 0;
 }
Output:
Number: 12
Enter data: 12.43
You entered: 12.43
Explanation of Program
In this program, two data members data1 and data2 and two member function int_data() andfloat_data() are defined under temp class. Two objects obj1 and obj2 of that class are declared. Function int_data() for the obj1 is executed using code obj1.int_data(12);, which sets 12 to thedata1 of object obj1. Then, function float_data() for the object obj2 is executed which takes data from user; stores it in data2 of obj2 and returns it to the calling function.
Note: In this program, data2 for object obj1 and data1 for object obj2 is not used and contains garbage value.
Data member according to Object in C++.
Defining Member Function Outside the Class
A large program may contain many member functions. For the clarity of the code, member functions can be defined outside the class. To do so, member function should be declared inside the class(function prototype should be inside the class). Then, the function definition can be defined using scope resolution operator ::. Learn more about defining member function outside the class.

Public, Protected and Private Inheritance in C++ Programming

Public, Protected and Private Inheritance in C++ Programming

You can declare a derived class from a base class with different access control, i.e., public inheritance, protected inheritance or private inheritance.
class base
{
.... ... ....
};

class derived : access_specifier base
{
.... ... ....
};

Things to remember while Using Public, Protected and Private Inheritance


  1. Protected and public members(data and function) of a base class are accessible from a derived class(for all three: public, protected and private inheritance).
  2. Objects of derived class with private and protected inheritance cannot access any data member of a base class.
  3. Objects of derived class with public inheritance can access only public member of a base class.
Public, protected and private inheritance in C++ programming with different access combinations

Summary of Public, Protected and Private Inheritance

Accessibility in Public Inheritance

Accessibilityprivateprotectedpublic
Accessible from own class?yesyesyes
Accessible from dervied class?noyesyes
Accessible outside dervied class?nonoyes

Accessibility in Protected Inheritance

Accessibilityprivateprotectedpublic
Accessible from own class?yesyesyes
Accessible from dervied class?noyesyes
Accessible outside dervied class?nonono

Accessibility in Private Inheritance

Accessibilityprivateprotectedpublic
Accessible from own class?yesyesyes
Accessible from dervied class?noyesyes
Accessible outside dervied class?nonono

OBJECT ORIENTED PROGRAMMING WITH C++ SYLLABUS

OBJECT ORIENTED PROGRAMMING WITH C++  (Common to CSE & ISE) 
Subject  Code:  10CS36     I.A. Marks    :  25 Hours/Week  :  04     Exam   Hours: 03 Total  Hours  :  52     Exam  Marks: 100 
PART – A
UNIT 1        6 Hours         
       Introduction: Overview of C++, Sample C++ program, Different data types, operators, expressions, and statements, arrays and strings, pointers & user- defined types Function Components, argument passing, inline functions, function overloading, recursive functions 

UNIT 2         7 Hours
 Classes & Objects – I: Class Specification, Class Objects, Scope resolution operator, Access members, Defining member functions, Data hiding, Constructors, Destructors, Parameterized constructors, Static data members, Functions   

UNIT 3          7Hours
 Classes & Objects –II:
Friend functions, Passing objects as arguments, Returning objects, Arrays of objects, Dynamic objects, Pointers to objects, Copy constructors, Generic functions and classes, Applications Operator overloading using friend functions such as +, - , pre-increment, post-increment, [ ] etc., overloading <<, >>.
 
UNIT 4           6Hours
 Inheritance – I: Base Class, Inheritance and protected members, Protected base class inheritance, Inheriting multiple base classes 

PART – B

UNIT 5           6 Hours
 Inheritance – II: Constructors, Destructors and Inheritance, Passing parameters to base class constructors, Granting access, Virtual base classes

UNIT 6           7 Hours
Virtual functions, Polymorphism: Virtual function, Calling a Virtual function through a base class reference, Virtual attribute is inherited, Virtual functions are hierarchical, Pure virtual functions, Abstract classes, Using virtual functions, Early and late binding. 
                  
UNIT 7       6 Hours
 I/O System Basics, File I/0: C++ stream classes, Formatted I/O, I/O manipulators, fstream and the File classes, File operations 

UNIT 8          7 Hours
 Exception Handling, STL: Exception handling fundamentals, Exception handling options STL: An overview, containers, vectors, lists, maps. 

Text Books:  1. Herbert Schildt: The Complete Reference C++, 4 th Edition, Tata McGraw Hill, 2003. 
Reference Books: 1. Stanley B.Lippmann, Josee Lajore: C++ Primer, 4 th Edition, Pearson Education, 2005. 2. Paul J Deitel, Harvey M Deitel: C++ for Programmers, Pearson Education, 2009. 3. K R Venugopal, Rajkumar Buyya, T Ravi Shankar: Mastering C++, Tata McGraw Hill, 1999.