Passing a class object as an argument in C ++

Suppose I had a class called foo, containing mostly data and a panel of classes that were used to display the data. So, if I have an instance of a foo object named foobar, how would I pass it to bar :: display ()? Something like void bar :: display (foobar & test)?

+4
source share
3 answers

Yeah almost. Or, if possible, use the const reference to indicate that the method is not going to modify the object passed as an argument.

class A; class B { // ... void some_method(const A& obj) { obj.do_something(); } // ... }; 
+9
source
 #include <iostream> class Foo { int m_a[2]; public: Foo(int a=10, int b=20) ; void accessFooData() const; }; Foo::Foo( int a, int b ) { m_a[0] = a; m_a[1] = b; } void Foo::accessFooData() const { std::cout << "\n Foo Data:\t" << m_a[0] << "\t" << m_a[1] << std::endl; } class Bar { public: Bar( const Foo& obj ); }; Bar::Bar( const Foo& obj ) { obj.accessFooData(); // i ) Since you are receiving a const reference, you can access only const member functions of obj. // ii) Just having an obj instance, doesn't mean you have access to everything from here ie, in this scope. It depends on the access specifiers. For example, m_a array cannot be accessed here since it is private. } int main( void ) { Foo objOne; Bar objTwo( objOne ) ; return 0 ; } 

Hope this helps.

+1
source

therefore, there are two ways to pass the class object (this is what you are asking) as an argument to the function i) Either pass a copy of the object to the function, so if any change made by the function in the object is not reflected in the original object

ii) Pass the base address of the object as an argument to the function. In the thsi method, if there are any changes made to the object by the calling function, they will also be reflected in the orignal object.

for example, look at this link , it clearly demonstrates the use of a pass by value and the passage through the link, the answer is clearly demonstrated in Jim Brissom.

0
source

Source: https://habr.com/ru/post/1333628/


All Articles