w********p 发帖数: 948 | 1 #include
using namespace std;
class Base
{
public:
Base(){ cout<<"Constructor: Base"<
~Base(){ cout<<"Destructor : Base"<
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"<
~Derived(){ cout<<"Destructor : Derived"<
};
int main()
{
Derived *Var = new Derived();
Base Var2;
Var2 = (Base) *Var;
delete Var;
return 0;
}
output:
Constructor: Base //1
Co |
X****r 发帖数: 3557 | 2 Derived *Var = new Derived();
// a. calls Base::Base() (1)
// b. calls Derived::Derived() (2)
Base Var2;
// calls Base::Base() (3)
Var2 = (Base) *Var;
// a. calls default copy constructor Base::Base(const Base&)
// to create a temporary Base object from *Var
// b. calls default assignment operator
// Base::operator =(const Base&) to assign this temporary
// object to Vars
// c. calls Base::~Base() for the temporary object. (4)
delete Var;
// a. calls Derived::~Derived() (5)
// b. calls Base::~Ba |
H***a 发帖数: 735 | 3 From Var2. When you exit main(), it will automatically call Base's
destructor to clean up the memory on stack. |
w********p 发帖数: 948 | 4 谢谢大牛。请问那本书上会解释道(4)
小小typo
// Base::operator ==(const Base&) to assign this temporary
应该是
// Base::operator =(const Base&) to assign this temporary |
w********p 发帖数: 948 | 5 you are right.
I did not understand what happen on " Var2 = (Base) *Var;"
【在 H***a 的大作中提到】 : From Var2. When you exit main(), it will automatically call Base's : destructor to clean up the memory on stack.
|
X****r 发帖数: 3557 | 6 对,我打错了,改过来了。
哪本书的话……你学到了东西以后还会记住这些东西都是从哪里学来的吗?:)
【在 w********p 的大作中提到】 : 谢谢大牛。请问那本书上会解释道(4) : 小小typo : // Base::operator ==(const Base&) to assign this temporary : 应该是 : // Base::operator =(const Base&) to assign this temporary
|
t****u 发帖数: 8614 | 7 4 is due to Var2 = (Base) *Var;
invoke an operator=(), you don't have it, so this is member-wise copy. A
temp object is still constructed through assignment operator, instead of
using default ctor. Since you slice the object, you only see the dtor of
base class.
5,6 is due to delete
7 is the "Base Var2;"
When out of the method scope, the dtor is called.
【在 w********p 的大作中提到】 : #include : using namespace std; : class Base : { : public: : Base(){ cout<<"Constructor: Base"<: ~Base(){ cout<<"Destructor : Base"<: }; : class Derived: public Base : {
|
w********p 发帖数: 948 | |
z***e 发帖数: 5393 | 9 如果你是用reference or pointer,就不会有temporary value.
但是 Var2 = (Base) *Var;
就差不多相当于:
{
Base base;
memcpy(&base, Var, sizeof(base));
call Var2.Base(base);
}
你给Base 自己加一个 Base(const Base&)随便打点东西出来就清楚了。
【在 w********p 的大作中提到】 : you are right. : I did not understand what happen on " Var2 = (Base) *Var;"
|