{"id":81838,"date":"2021-07-22T09:00:25","date_gmt":"2021-07-22T03:30:25","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81838"},"modified":"2021-07-22T09:00:25","modified_gmt":"2021-07-22T03:30:25","slug":"constructor-destructor-in-cpp","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/","title":{"rendered":"Constructor in C++ | Destructor in C++"},"content":{"rendered":"<p>In this article, we will learn about Constructors and Destructors in C++.<\/p>\n<h3>Constructors in C++<\/h3>\n<p>When an object is created, a special member function of the class, known as constructor, is called automatically. Constructors are extremely useful for initializing class objects.<\/p>\n<h4>Properties of a Constructor<\/h4>\n<ul>\n<li>When we create an object, it is called automatically.<\/li>\n<li>It has the same name as that of the class.<\/li>\n<li>It has no return type.<\/li>\n<li>It cannot be inherited, although the derived class can call it.<\/li>\n<li>It cannot be const.<\/li>\n<li>It cannot be virtual.<\/li>\n<li>It must be declared inside public in a class.<\/li>\n<li>It can have default parameters.<\/li>\n<li>It\u2019s address is inaccessible.<\/li>\n<\/ul>\n<p>If the user does not define a constructor, the compiler implicitly generates a default constructor.<\/p>\n<h3>Types of Constructors in C++<\/h3>\n<h4>1. Default Constructor in C++<\/h4>\n<p>A default constructor is a constructor that does not have parameters.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class_name() {\n  \/\/statements\n}\n<\/pre>\n<p><strong>Example of default constructor in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Rectangle {\n    public:\n    float length, breadth;\n    Rectangle() {           \/\/Default Constructor\n        length = 10;\n        breadth = 6.5;\n    }\n};\n\nint main() {\n  Rectangle r;\n  cout&lt;&lt;\"length = \"&lt;&lt;r.length&lt;&lt;endl;\n  cout&lt;&lt;\"breadth = \"&lt;&lt;r.breadth;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">length = 10<br \/>\nbreadth = 6.5<\/div>\n<h4>2. Parameterized Constructor in C++<\/h4>\n<p>We can also pass parameters to a constructor. A constructor that has parameters is called a parameterized constructor. These parameters are used to set initial values to the data members of an object as soon as it is created.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class_name(parameter1, parameter2, \u2026) {\n  \/\/statements\n}\n<\/pre>\n<p><strong>Example of parameterized constructor in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Rectangle {\n    private:\n    float length, breadth;\n    \n    public:\n    Rectangle(float l, float b) {           \/\/Parameterized Constructor\n        length = l;\n        breadth = b;\n    }\n    float Area(){\n        return length*breadth;\n    }\n};\n\nint main() {\n  Rectangle r(12.64, 7);\n  cout&lt;&lt;\"Area = \"&lt;&lt;r.Area();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Area = 88.48<\/div>\n<p>While creating an object in a parameterized constructor, we must pass the initial values as parameters. We can call constructors either explicitly or implicitly.<\/p>\n<p>Explicit call: Rectangle r = Rectangle(12.64, 7);<br \/>\nImplicit call: Rectangle r(12.64, 7);<\/p>\n<h5>Uses of parameterized constructor<\/h5>\n<p>Using parameterized constructor, we can initialize different objects with different values.<br \/>\nIt is used to achieve constructor overloading.<\/p>\n<h4>Constructor with Default Arguments<\/h4>\n<p>In C++, we can define constructors with default arguments.<\/p>\n<p><strong>Example of constructor with default arguments in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Rectangle {\n    private:\n    float length, breadth;\n    public:\n    Rectangle(float l=10, float b=5){       \/\/Constructor with default arguments\n        length = l;\n        breadth = b;\n    }\n    void print() {\n        cout&lt;&lt;\"Length of rectangle = \"&lt;&lt;length&lt;&lt;endl;\n        cout&lt;&lt;\"Breadth of rectangle = \"&lt;&lt;breadth&lt;&lt;endl;\n    }\n};\n\nint main() {\n  Rectangle r(20.5);\n  r.print();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Length of rectangle = 20.5<br \/>\nBreadth of rectangle = 5<\/div>\n<h4>3. Copy Constructor in C++<\/h4>\n<p>A constructor that initializes an object with the use of another object of the same class is called a copy constructor. It basically copies data of one object to another.<\/p>\n<p><strong>Syntax of a copy constructor<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class_name (const class_name &amp;obj) {\n  \/\/statements\n}\n<\/pre>\n<p><strong>Example of copy constructor in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Square {\n    public:\n    float side;\n    Square(float s) {           \n        side = s;\n    }\n    Square(const Square &amp;obj) {       \/\/Copy Constructor\n        side = obj.side;\n    }\n};\n\nint main() {\n  Square s1(4.5);\n  Square s2 = s1;     \/\/Copy constructor called\n  cout&lt;&lt;\"side of 1st square = \"&lt;&lt;s1.side&lt;&lt;endl;\n  cout&lt;&lt;\"side of 2nd square = \"&lt;&lt;s2.side;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">side of 1st square = 4.5<br \/>\nside of 2nd square = 4.5<\/div>\n<p><strong>Remember that<\/strong><\/p>\n<p>As a best practice, we should define a default constructor if we are defining one or more non-default constructors. This is so because the compiler will not automatically generate a default constructor in this situation. We can also use constructors to execute a default code.<\/p>\n<h3>Constructor Overloading in C++<\/h3>\n<p>A class in C++ can have many constructors with the same name as long as each has a different set of parameters. Such constructors are called overloaded constructors.<\/p>\n<p><strong>Example of constructor overloading in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Rectangle {\n    private:\n    float length, breadth;\n    public:\n    Rectangle() {\n        length = 0;\n        breadth = 0;\n    }\n    Rectangle(float l, float b) {\n        length = l;\n        breadth = b;\n    }\n    void print() {\n        cout&lt;&lt;\"Length of rectangle = \"&lt;&lt;length&lt;&lt;endl;\n        cout&lt;&lt;\"Breadth of rectangle = \"&lt;&lt;breadth&lt;&lt;endl;\n    }\n};\n\nint main() {\n  Rectangle r1;\n  Rectangle r2(20.5, 12);\n  r1.print();\n  r2.print();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Length of rectangle = 0<br \/>\nBreadth of rectangle = 0<br \/>\nLength of rectangle = 20.5<br \/>\nBreadth of rectangle = 12<\/div>\n<h3>Destructors in C++<\/h3>\n<p>A special member function of a class that destroys or deletes an object is called a destructor.<\/p>\n<p><strong>Syntax<\/strong>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class_name() {\n  \/\/statements\n}\n<\/pre>\n<p>A destructor is called when an object is no longer in scope, such as when a function ends, program ends, delete operator is called or a block having local variables ends.<\/p>\n<h3>Properties of a destructor in C++<\/h3>\n<ul>\n<li>When an object is destroyed, it is called automatically.<\/li>\n<li>It has the same name as the class.<\/li>\n<li>It is preceded by a tilde (~).<\/li>\n<li>It does not have any parameters.<\/li>\n<li>It has no return type.<\/li>\n<li>It cannot be static or const.<\/li>\n<li>It must be declared inside public in a class.<\/li>\n<li>It\u2019s address is inaccessible to the programmer.<\/li>\n<\/ul>\n<p>A destructor is useful for freeing resources before exiting a program, such as closing files, releasing memory space, etc.<\/p>\n<p><strong>Example of destructor in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Student {\n    private:\n    int rollno;\n    public:\n    Student(){          \/\/constructor\n        rollno = 0;\n        cout&lt;&lt;\"Constructor called\"&lt;&lt;endl;\n    }\n    ~Student(){         \/\/destructor\n        cout&lt;&lt;\"Destructor called\";\n    }\n};\n\nint main() {\n    Student s;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Constructor called<br \/>\nDestructor called<\/div>\n<p><strong>Note that<\/strong><\/p>\n<ul>\n<li>We can have only one destructor for a class.<\/li>\n<li>If we don&#8217;t specify a destructor in the class, the compiler produces a default one for us. However, when we dynamically allocate memory or there is a pointer in the class, we should declare a destructor to prevent memory leaks.<\/li>\n<\/ul>\n<h4>Virtual Destructor in C++<\/h4>\n<p>When there is inheritance, we declare the destructor of the base class as virtual. This is so because the non-virtual destructor of the base class has undefined behavior. Making the base class destructor virtual ensures that the derived class objects are properly deleted.<\/p>\n<p>We write this as<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">virtual ~BaseClassName() {\n  \/\/statements\n}\n<\/pre>\n<h3>Summary<\/h3>\n<p>We have learnt constructors and destructors in C++ in this article. These are special member functions of a class.<br \/>\nA constructor is called when an object is created.<\/p>\n<p>There are three types of constructors, default, parameterized and copy constructor. We learnt about all three using examples. We also discussed constructor overloading in C++.<\/p>\n<p>A destructor is called when an object is deleted. We saw an example to better understand a destructor.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about Constructors and Destructors in C++. Constructors in C++ When an object is created, a special member function of the class, known as constructor, is called automatically. Constructors&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":82933,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[3782,3783,3784],"class_list":["post-81838","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-constructor-in-c","tag-destructor-in-c","tag-types-of-constructor-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Constructor in C++ | Destructor in C++ - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about constructors and destructors in C++. There are three types of constructors, default, parameterized and copy constructor.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Constructor in C++ | Destructor in C++ - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about constructors and destructors in C++. There are three types of constructors, default, parameterized and copy constructor.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-22T03:30:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/C-Constructor-Destructor.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Constructor in C++ | Destructor in C++ - TechVidvan","description":"Learn about constructors and destructors in C++. There are three types of constructors, default, parameterized and copy constructor.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"Constructor in C++ | Destructor in C++ - TechVidvan","og_description":"Learn about constructors and destructors in C++. There are three types of constructors, default, parameterized and copy constructor.","og_url":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-22T03:30:25+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/C-Constructor-Destructor.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Constructor in C++ | Destructor in C++","datePublished":"2021-07-22T03:30:25+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/"},"wordCount":764,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/C-Constructor-Destructor.jpg","keywords":["Constructor in C++","Destructor in C++","Types of Constructor in C++"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/","url":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/","name":"Constructor in C++ | Destructor in C++ - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/C-Constructor-Destructor.jpg","datePublished":"2021-07-22T03:30:25+00:00","description":"Learn about constructors and destructors in C++. There are three types of constructors, default, parameterized and copy constructor.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/C-Constructor-Destructor.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/07\/C-Constructor-Destructor.jpg","width":1200,"height":628,"caption":"C++ Constructor &amp; Destructor"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/constructor-destructor-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Constructor in C++ | Destructor in C++"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81838","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81838"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81838\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/82933"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81838"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81838"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81838"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}