How are objects passed as parameters Why is it said that the

How are objects passed as parameters? Why is it said that the actual parameter and the formal parameter become aliases.

Solution

==================================================================

---------------

Answer:
---------------

   Objects are passed by reference of the object from the caller. Objects typically holds reference (Address mapped to memory).
   Since Objects holds memory address, which can not be send as pass by value, It must be send to function using pass by reference.
   When an object is given as parameter to a function caller. The actual parameter will be passed as a reference and formal parameter becomes
   alias during the function call.
  
   ------------------------------------------------
   Let us consider this example:
   ------------------------------------------------

  
   #include<iostream>
   #include<string>

   using namespace std;
   //Rectangle class
   class Rectangle {
      
       public:

           int l;
           int b;
          
           //Parametized constrcutor
           Rectangle(int lParam,int bParam) {

               l = lParam;
               b = bParam;
           }
      
   };

   //A method which takes objects as argument
   void printRectangleDimensions(Rectangle rec) {

      
       cout<<\" --- Rectangle Dimensions --- \ \";
       cout<<\"Length: \"<<rec.l<<endl;
       cout<<\"Breadth: \"<<rec.b<<endl;
   }

   void main() {
      

       Rectangle rec(10,20);
       printRectangleDimensions(rec);
   }
  

       In this example, Rectangle class defined and it is initialized using Parametized constrcutor.
       void printRectangleDimensions(Rectangle rec) is writted inorder to ellustrute the example of pass by reference for object fields.
       When the statement printRectangleDimensions(rec); is called, the rec of type Rectangle and its address being passed to caller.
       Caller can have an alias in this example same alias is used. And the object is accessed, Finally rectangle dimensions are printed on console.
==================================================================

How are objects passed as parameters? Why is it said that the actual parameter and the formal parameter become aliases.Solution ================================
How are objects passed as parameters? Why is it said that the actual parameter and the formal parameter become aliases.Solution ================================

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site