在类中由几个特殊而重要的函数:constructor,copy constructor,destructor,assignment operator(=).说它们特殊是因为它们负责类对象的创建,复制,赋值和销毁.如果用户自己没有在类中定义这几个函数,那么编译器会自动生成它们的默认版本(default version).一下内容转载自这里.
Constructor
usage:
features:
- constructor has same name as the class itself
- constructor don't have return type
- if we don't specify a constructor,c++ compiler generates adefault constructor for us
default constructor
In C++, the standard describes the defaultconstructor for a class as a constructor that can be called with no arguments(this includes a constructor whose parameters all have default arguments)
Remember that each class can have at mostone default constructor, either one without parameters, or one whose allparameters have default values.
Compiler doesn’t create a defaultconstructor if we write any constructor even if it is copy constructor. Butreverse is not true. Compiler creates a copy constructor if we don’t write ourown.
- without any arguments or with default value for every argument.
- if we define our own constructor, compiler doesn’t create the default constructor.
- If a class has no explicitly defined constructors, the compiler will implicitly declare and define a default constructor for it. This implicitly defined default constructor is equivalent to an explicitly defined one with an empty body.
- If constructors are explicitly defined for a class,but they are all non-default, the compiler will not implicitly define a defaultconstructor, leading to a situation where the class does not have a defaultconstructor. This is the reason for a typical error,
Copy Constructor
a member function which initializesan object using another object of the same class,Compiler also creates a copyconstructor if we don’t write our own copy constructor.Unlike defaultconstructor, body of compiler created copy constructor is not empty, it copiesall data members of passed object to the object which is being created(this isshallow copy).
function prototype:
ClassName (const ClassName &old_object)
when is copy constructor called?
- when an object of the class is returned by value
- when an object of the class is passed(to a function)by value as an argument
- when an object is constructed based on another object of the same class
- when compiler generates a temporary object
when is user defined copy constructor needed?
runtime allocation of resource like new, file handle,a network connection...etc
default copy constructor does only shllow copy
deep copy is possible only with user defined copy constructor
copy constructor vs assignment operator
- copy constructor is called when a new boject is created from an existing object,as a copy of the existing object.
- assignment operator is called when an already initialized object is assigned a new value from another existing object.
myclass t1,t2;
myclass t3 = t1;//copy constructor
myclass t4(t1);//copy constructor
t2 = t1;//assignment operator
can we make copy constructor private?
yes,if so,objects of that class would become non-copyable.why argument to a copy constructor must be passed as a reference?
A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be pass by value.why argument to a copy constructor should be const?
Destructor
When is destructor called?
A destructor function is called automatically when the object goes out of scope:- the function ends
- the program ends
- a block containing local variables ends
- a delete operator is called
When do we need to write a user-defined destructor?
If we do not write our own destructor in class, compiler creates a default destructor for us. The default destructor works fine unless we have dynamically allocated memory or pointer in class. When a class contains a pointer to memory allocated in class, we should write a destructor to release memory before the class instance is destroyed. This must be done to avoid memory leak.Can a destructor be virtual?
Yes, In fact, it is always a good idea to make destructors virtual in base class when we have a virtual function.Can a destructor be private?
Yes,wheneverwe want to control destruction of objects of a class, we make the destructorprivate. This situation is ok only for dynamically created objects, it mayhappen that you pass a pointer to the object to a function and the functiondeletes the object. If the object is referred after the function call, thereference will become dangling.
#include <iostream>
class Test{
private:
~Teset(){}
friend void destructor(Test*);
};
void destructor(Test*ptr){
delete ptr;
}
int main(int argc, char *argv[])
{
//proper use
Test *ptr = new Test;
destructor(ptr);
//1 compiler error:local variable ‘test’ cannot be destructed because the destructor is private.
// Test test;
//2 copiler error
// Test *t = new Test;//ok,because untill now,hasn't call destuctor
// delete t; //error:destructor is called
return 0;
}
Playing with destructor
预测下面程序的输出
#include <iostream>
using namespace std;
int i;
class A
{
public:
~A()
{
i=10;
}
};
int foo()
{
i=3;
A ob;
return i;
}//此处调用ob的析构函数
int main()
{
cout << "i = " << foo() << endl;
return 0;
}
输出结果是:i = 3
为什么是3而不是10呢?
在函数foo()中,ob的析构函数会在它的生命周期结束时调用,即在foo()函数结束处调用,所以在ob调用析构函数改变i之前,i的值作为3返回了.
如何才能让返回值是10呢?
修改foo()函数:
int foo()
{
i = 3;
{
A ob;
}
return i;
}
总结:
- default copy constructor, default assignment operator, and default destructor are ok if a class has no pointer or any other runtime resources, because shallow copy is probably sufficient.or,if your class has pointers or other dynamic allocate resources,you need define copy constructor yourself,thus it is almost certain that you will need a destructor and override the assignment operator.