类的几大函数

来源:互联网 发布:漫画控无网络连接 编辑:程序博客网 时间:2024/06/06 01:54

在类中由几个特殊而重要的函数:constructor,copy constructor,destructor,assignment operator(=).说它们特殊是因为它们负责类对象的创建,复制,赋值和销毁.如果用户自己没有在类中定义这几个函数,那么编译器会自动生成它们的默认版本(default version).一下内容转载自这里.

Constructor

 when object(instance of class)create,it is called automatically.

usage:

initialize data members,in the same order as they appear in the class declaration.

features:

  1. constructor has same name as the class itself
  2. constructor don't have return type
  3. 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.


  1.  without any arguments or with default value for every argument.
  2. if we define our own constructor, compiler doesn’t create the default constructor.
  3. 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.
  4. 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?

  1. when an object of the class is returned by value
  2. when an object of the class is passed(to a function)by value as an argument
  3. when an object is constructed based on another object of the same class
  4. when compiler generates a temporary object

 when is user defined copy constructor needed?

the default copy constructor works well in general.we need to define our own constructoronly if an object has pointers or any
 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

  1. copy constructor is called when a new boject is created from an existing object,as a copy of the existing object.
  2. 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

Destructor is a member function which destructs or deletes an object. there can only one destructor in a class with classname preceded by ~, no parameters and no return type.

When is destructor called?

A destructor function is called automatically when the object goes out of scope:
  1.  the function ends
  2.  the program ends
  3.  a block containing local variables ends
  4.  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 fineunless 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;}




总结:

  1. 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.



原创粉丝点击