954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

passing objects as function parameters

hhey sir i need some information about his topic urgently

sarvari
Newbie Poster
1 post since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

what do you want to know about it? c++ objects are normally passed by reference to avoid expensive duplication and to let other functions use the same object as the calling function.

class MyClass
{
  // blabla
};

void foo(MyClass& obj)
{
    // class passed by reference
}

int main()
{
    MyClass myclass; // create an instance of the class
    foo(myclass); // pass it to another function
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

They can also be passed as pointers, if you want to use them. Thought I believe it's considered better to use references over pointers when possible.

class MyClass
{
  // blabla
};

void foo(MyClass* obj)
{
    // class passed by reference
}

int main()
{
    MyClass myclass; // create an instance of the class
    foo(&myclass); // pass it to another function

    //or....
   MyClass* myclass = new MyClass;//create a pointer to the class and allocate an object at its location
   foo(myclass);//call the function
   delete myclass;//deallocate the object
}
CoolGamer48
Posting Pro in Training
401 posts since Jan 2008
Reputation Points: 77
Solved Threads: 40
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You