How to pass objects to functions in C++?

后端 未结 7 884
無奈伤痛
無奈伤痛 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:07

    Since no one mentioned I am adding on it, When you pass a object to a function in c++ the default copy constructor of the object is called if you dont have one which creates a clone of the object and then pass it to the method, so when you change the object values that will reflect on the copy of the object instead of the original object, that is the problem in c++, So if you make all the class attributes to be pointers, then the copy constructors will copy the addresses of the pointer attributes , so when the method invocations on the object which manipulates the values stored in pointer attributes addresses, the changes also reflect in the original object which is passed as a parameter, so this can behave same a Java but dont forget that all your class attributes must be pointers, also you should change the values of pointers, will be much clear with code explanation.

    Class CPlusPlusJavaFunctionality {
        public:
           CPlusPlusJavaFunctionality(){
             attribute = new int;
             *attribute = value;
           }
    
           void setValue(int value){
               *attribute = value;
           }
    
           void getValue(){
              return *attribute;
           }
    
           ~ CPlusPlusJavaFuncitonality(){
              delete(attribute);
           }
    
        private:
           int *attribute;
    }
    
    void changeObjectAttribute(CPlusPlusJavaFunctionality obj, int value){
       int* prt = obj.attribute;
       *ptr = value;
    }
    
    int main(){
    
       CPlusPlusJavaFunctionality obj;
    
       obj.setValue(10);
    
       cout<< obj.getValue();  //output: 10
    
       changeObjectAttribute(obj, 15);
    
       cout<< obj.getValue();  //output: 15
    }
    

    But this is not good idea as you will be ending up writing lot of code involving with pointers, which are prone for memory leaks and do not forget to call destructors. And to avoid this c++ have copy constructors where you will create new memory when the objects containing pointers are passed to function arguments which will stop manipulating other objects data, Java does pass by value and value is reference, so it do not require copy constructors.

提交回复
热议问题