Constructor
have the same name as class, non return type What a constructor does ?
1 create a symbol for the object
2 reserve memory space for the object
3 initialize the members
ex :
class A{
public:
A(){cout<< "Constructor"<<endl;};
~A(){cout<< "destruct"<<endl;}
}
int main(){
A a; // ------> Constructor is
......
// ------> Destructor is called
}
Destructor
destructor cannot have parameters (cannot be overloaded) : one class can have only one destructor. If user not define, compiler will generate a destructor.destructor is called when the object is destroyed. So when we destroy an object ?
(scope and lifecycle)
1: in amethod : you defined a local object variable, when the method finished, this local object will be destroyed
2 : static local variable and global variable will not be destroyed until the process is finished : the end of the main or when we call exit
1 Base class' destructor and sub class' destructor
the order of calling destructor is :
subclass' destructor --> base class' destructor
the order of calling constructor is Converse :
base class' constructor --> subclass' constructor
2 if the base class' destructor is not virtual :
the subclass' destructor will not be called, and the subclass' own members will not be released after destruction.ex :
class Base{
private:
int* number_ = new int(0) ;
public:
Base() {};
~Base(){ delete number_;};
}
class Sub:Base{
private:
float* speed_ = new float(0f);
public :
Sub(int num, float speed):Base(num):speed_(speed){};
~Sub(){delete speed_;};
}
3 destructor will be called automatically in the end :
And the calling order is revered from creating order : a stackint main(){
A a(0);
A b(1);
A c(2);
.....
.....
///--> in the end, the destruct order is : c,b,a ---> stack !
}
but!!! when you use new, it's different!!!
int main(){ A * a; a = new A(); return 0;///--> in the end, there is non destructor called !! }For C++, if you created the object with new, then it's your responsibility to release the memory of this object:
int main(){ A * a; a = new A(); delete a; return 0; }4 destructor with int method :
class A{ public: A() { cout << "constructor" << endl; } ~A() { cout << "destructor" << endl; }};void function(A a)//--pass-by-value{ }int main(){ A a; function(a); return 0;} output : constructordestructordestructor!! tow times of destructor:function did a shallow copy, but the function will trait the object as an local object and call its destructor ---> illegal! we do not want to destroy the object so we need to use : pass-by-reference-to-const for parameter :
void function(const A& a)//--pass-by-reference-to-const{ }
No comments:
Post a Comment