passing by value -> constructor ?

Started by
2 comments, last by bilsa 19 years, 10 months ago
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!
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&) { ... }};
thank you
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;
}

This topic is closed to new replies.

Advertisement