Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

bilsa

passing by value -> constructor ?

This topic is 5282 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey guys, I''m wondering which constructor is callse when passing an Object like this by value to a function:
class Object {
public:
Object(int value) {
//....

}

Object(const char* value) {
//....

}

Object(Object* pCopy) {
m_Parent = pCopy;
m_Parent->m_nRefs++;
//...

}

~Object() {

if(m_Parent == 0) {
//delete some stuff

} else {
m_Parent->m_nRefs--;
}

}

int m_nRefs;

private:
Object* m_Parent;
}
Now I can do like this: Object o1 = 10; Object o2 = "Test"; void testFunction(Object o) {...} //which constructor is called when passing by value like this? testFunction(o1); thank you!

Share this post


Link to post
Share on other sites
Advertisement
In that case the copy constructor is called, since you didn''t write one, the compiler generated constructor is used. The copy constructor has the following form:

class Object {
Object(const Object&) { ... }
};

Share this post


Link to post
Share on other sites
You have to be careful. The default copy constructor will do a member-wise copy. That means that your m_Parent *pointer* will be copied, but it will still point to the same Object as your original pointer. This is very dangerous. I advocate avoiding pointers whenever you can. Example:

// this code assumes you didn''t write a copy constructor
...
Object o1;
testFunction(o1);
o1.m_Parent; // points to junk now
...


// inside testFunction
void testFunction(Object o)
{
delete o->m_Parent;
}

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!