T
trying_to_learn
i am on the chapter on copy construction in C++
in the code (see below), the author says if u pass the object by value
as in HowMany h2 = f(h); ....then a bitwise object is created w/o
calling the constructor of the class. However he says when we leave
scope of function HowMany f(HowMany x) then the destructor is called.
why this inconsistency?. Accdng to me even the destructor should *not*
be called. i can understand that bit wise copy means a 'C' like method
of simply pushing the arguments into stack. accdng to me when fn 'f' is
over, it should simply mean that stack (local object that was made by
value)is popped out without calling its detructor.
i hope im not asking a stupid qn. but im confused abt this fundamental.
-----------------*heres the code*------------------------------
class HowMany {
static int objectCount;
public:
HowMany() { objectCount++; }
static void print(const string& msg = "") {
if(msg.size() != 0) out << msg << ": ";
out << "objectCount = "
<< objectCount << endl;
}
~HowMany() {
objectCount--;
print("~HowMany()");
}
};
int HowMany:bjectCount = 0;
// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}
int main() {
HowMany h;
HowMany:rint("after construction of h");
HowMany h2 = f(h);
HowMany:rint("after call to f()");
} ///:~
in the code (see below), the author says if u pass the object by value
as in HowMany h2 = f(h); ....then a bitwise object is created w/o
calling the constructor of the class. However he says when we leave
scope of function HowMany f(HowMany x) then the destructor is called.
why this inconsistency?. Accdng to me even the destructor should *not*
be called. i can understand that bit wise copy means a 'C' like method
of simply pushing the arguments into stack. accdng to me when fn 'f' is
over, it should simply mean that stack (local object that was made by
value)is popped out without calling its detructor.
i hope im not asking a stupid qn. but im confused abt this fundamental.
-----------------*heres the code*------------------------------
class HowMany {
static int objectCount;
public:
HowMany() { objectCount++; }
static void print(const string& msg = "") {
if(msg.size() != 0) out << msg << ": ";
out << "objectCount = "
<< objectCount << endl;
}
~HowMany() {
objectCount--;
print("~HowMany()");
}
};
int HowMany:bjectCount = 0;
// Pass and return BY VALUE:
HowMany f(HowMany x) {
x.print("x argument inside f()");
return x;
}
int main() {
HowMany h;
HowMany:rint("after construction of h");
HowMany h2 = f(h);
HowMany:rint("after call to f()");
} ///:~