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

📅  最后修改于: 2021-05-30 06:33:03             🧑  作者: Mango

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

句法:

ClassName()
   {
     //Constructor's Body 
   } 

析构函数
像构造函数一样,解构函数也是类的成员函数,其名称与以tilde(〜)运算符开头的类名称相同。它有助于释放对象的内存。在释放或删除类的对象时调用它。在一个类中,总是有一个没有任何参数的析构函数,因此无法对其进行加载。始终以相反的构造函数顺序调用它。如果一个类被另一个类继承,并且两个类都具有析构函数,则将先调用子类的析构函数,然后再调用父类或基类的析构函数。

句法:

~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等的更多准备工作,请参阅“完整面试准备课程”