Passing a class object as an argument in C++

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

Answers


Yes, almost. Or, if possible, use a const reference to signal 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();
    }
    // ...
};

#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 i.e., 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.


so there are two way of passing class object(it is what you are asking) as a function argument i) Either pass the copy of object to the function, in this way if there is any change done by the function in the object will not be reflected in the original object

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

for example have a look at this link, it clearly demonstrate the usage of pass by value and pass by reference is clearly demonstrated in Jim Brissom answer.


Need Your Help

How can I store the state of the pseudo-random generator in Perl?

perl srand random-seed

Is there a way to store the current state of the built in pseudo-random number generator in Perl so that when my program is run again, it can pick up the sequence from where it left off rather than

Why is this SWFUpload -> Presigned Post to S3 setup not working? (Rails)

ruby-on-rails amazon-s3 swfupload

I am trying to do a presigned post to S3 with SWFUpload and AWS-SDK. Long story short, it's not working.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.