-5
 #include<iostream>

  using namespace std;

    class A
   {

   public:
   A(int x)
   {
   a=x;
    }

   int a;
    };

  void fun(A temp)
  {
  cout<<temp.a<<endl;
  }

  int main()
  {
  fun(1);
   }

Here we are passing primitive values to fun method and catching using object of class A. can anyone explain me how above code works and using which concept?

Nirav
  • 3
  • 2

2 Answers2

0

Class A has a constructor which receives an integer as a parameter.

Therefore, the integer parameter passed to fun is automatically casted to A.

In this automatic cast process, an A object (called temp) is created, and it's field 'a' is initialized with 1.

ibezito
  • 5,782
  • 2
  • 22
  • 46
  • Thanks for explaining, but one more doubt what would happen during cast process if we have more than one data members in A class and we are just passing 1 value? – Nirav May 14 '17 at 10:34
  • the automatic casting will work according to how you defined you constructor. – ibezito May 14 '17 at 10:40
0

I commented the code for you and made it a bit more clear to read. Read the comments from (1) -> (5).

#include <iostream>

using namespace std;

class A {

public:
    A(int x) // (3): gets called by f to initialize an object of class A with x=1
    {
        a = x;
    }

    int a;
};

void fun(A temp) // (2): Assumes 1 is a type class A. But it hasn't yet been initialized. So it calls Constructor. (tmp = new A(1))
{
    // (4): Now temp is an object of class A
    cout << temp.a << endl; // Prints temp.a
    // (5): temp object is getting destroyed.
}

int main()
{
    fun(1); // (1): Calls fun() with argument of 1
}
Panos
  • 1,764
  • 21
  • 23