📜  C++中构造函数和析构函数的区别

📅  最后修改于: 2021-09-16 10:21:21             🧑  作者: Mango

构造函数
构造函数是与类名同名的类的成员函数。它有助于初始化一个类的对象。它可以接受或不接受参数。它用于为类的对象分配内存。每当创建类的实例时都会调用它。它可以带参数或不带参数手动定义。类中可以有很多构造函数。它可以被重载,但不能被继承或虚拟。有一个复制构造函数的概念,用于从另一个对象初始化一个对象。

句法:

ClassName()
   {
     //Constructor's Body 
   } 

析构函数
与构造函数一样,析构函数也是类的成员函数,该类的名称与类名相同,前面带有波浪号 (~)运算符。它有助于释放对象的内存。在释放或删除类的对象时调用它。在一个类中,总是有一个没有任何参数的析构函数,所以它不能被重载。它总是以与构造函数相反的顺序调用。如果一个类被另一个类继承,并且两个类都有一个析构函数,那么首先调用子类的析构函数,然后是父类或基类的析构函数。

句法:

~ClassName()
   { 
   }

注意:如果我们没有为类内的成员指定任何访问修饰符,那么默认情况下,成员的访问修饰符将为 Private。

构造函数和析构函数的示例/实现:

class Z
{
public:
    // constructor
    Z()
    {
        cout<<"Constructor called"<

输出:

Constructor called
Constructor called
Destructor called
Destructor called 

C++中构造函数和析构函数的区别:

S.NO Constructor Destructor
1. Constructor helps to initialize the object of a class. Whereas destructor is used to destroy the instances.
2. It is declared as Classname( arguments if any ){Constructor’s Body }. Whereas it is declared as ~ ClassName( no arguments ){ };.
3. Constructor can either accept an arguments or not. While it can’t have any arguments.
4. A constructor is called when an instance or object of a class is created. It is called while object of the class is freed or deleted.
5. Constructor is used to allocate the memory to an instance or object. While it is used to deallocate the memory of an object of a class.
6. Constructor can be overloaded. While it can’t be overloaded.
7. The constructor’s name is same as the class name. Here, it’s name is also same as the class name preceded by tiled (~) operator.
8. In a class, there can be multiple constructors. While in a class, there is always a single destructor.
9. There is a concept of copy constructor which is used to initialize a object from another object. While here, there is no copy constructor concept.
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程