How to pass objects to functions in C++?

后端 未结 7 887
無奈伤痛
無奈伤痛 2020-11-21 04:55

I am new to C++ programming, but I have experience in Java. I need guidance on how to pass objects to functions in C++.

Do I need to pass pointers, references, or no

7条回答
  •  无人共我
    2020-11-21 05:06

    There are three methods of passing an object to a function as a parameter:

    1. Pass by reference
    2. pass by value
    3. adding constant in parameter

    Go through the following example:

    class Sample
    {
    public:
        int *ptr;
        int mVar;
    
        Sample(int i)
        {
            mVar = 4;
            ptr = new int(i);
        }
    
        ~Sample()
        {
            delete ptr;
        }
    
        void PrintVal()
        {
            cout << "The value of the pointer is " << *ptr << endl
                 << "The value of the variable is " << mVar;
       }
    };
    
    void SomeFunc(Sample x)
    {
    cout << "Say i am in someFunc " << endl;
    }
    
    
    int main()
    {
    
      Sample s1= 10;
      SomeFunc(s1);
      s1.PrintVal();
      char ch;
      cin >> ch;
    }
    

    Output:

    Say i am in someFunc
    The value of the pointer is -17891602
    The value of the variable is 4

提交回复
热议问题