{"id":4799,"date":"2025-01-29T09:10:00","date_gmt":"2025-01-29T04:10:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=4799"},"modified":"2026-03-18T08:22:30","modified_gmt":"2026-03-18T03:22:30","slug":"understanding-constructors-in-c","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/01\/29\/understanding-constructors-in-c\/","title":{"rendered":"Constructors and Destructors in C++"},"content":{"rendered":"\n<p>C++ gives every object a clear life story: it\u2019s created, used, and then destroyed. To make this safe and predictable, the language runs a special function at birth (to initialize the object) and another at death (to clean up resources).<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Constructors &amp; Destructors in C++ Explained | OOP Tutorial | Object Initialization &amp; Lifecycle\" width=\"640\" height=\"360\" src=\"https:\/\/www.youtube.com\/embed\/YF8D5lj1Cqk?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Constructors in C++<\/h2>\n\n\n\n<p>Constructors exist to prevent uninitialized state, to let callers pass meaningful values at creation time, and to centralize setup logic in one place. In practice, you\u2019ll use two common kinds;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Default (non-parameterized)<\/strong><\/li>\n\n\n\n<li><strong>Parameterized<\/strong><\/li>\n<\/ul>\n\n\n\n<p>You may define <strong>multiple constructors<\/strong> for the same class (<strong>overloading<\/strong>) so the same class can be created in different valid ways.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>A constructor in C++ is a special member function with the same name as its class, has no return type, and is invoked automatically when an object is created to initialize its data members.<\/p>\n<\/blockquote>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax and core rules (quick reference)<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ClassName {\npublic:\n    ClassName();                 \/\/ default (non-parameterized)\n    ClassName(int x, int y);     \/\/ parameterized\n};\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The name must exactly match the class; there is <strong>no return type<\/strong>.<\/li>\n\n\n\n<li>You may overload constructors with different parameter lists.<\/li>\n\n\n\n<li>Prefer <strong>member-initializer lists<\/strong> (<code>: a(x), b(y)<\/code>) so members are constructed directly.<\/li>\n\n\n\n<li>Members are initialized in the <strong>order they are declared<\/strong> in the class, not the order listed in the initializer list.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1 \u2014 Default constructor <\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Student {\nprivate:\n    int a;        \/\/ internal\/private\npublic:\n    int b;        \/\/ visible\/public\n\n    \/\/ Default constructor: give safe defaults\n    Student(){\n             a=0;\n             b=0 \n        }\n\n    void display() const {\n        cout &lt;&lt; \"The value of a and b is: \" &lt;&lt; a &lt;&lt; \" and \" &lt;&lt; b &lt;&lt; '\\n';\n    }\n};\n\nint main() {\n    Student s;     \n    s.display();   \n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p><strong>What to notice:<\/strong> creating <code>Student s;<\/code> automatically calls <code>Student()<\/code>. Using an initializer list builds <code>a<\/code> and <code>b<\/code> directly as <code>0<\/code>, so there\u2019s no \u201ccreate-then-assign\u201d waste and no risk of reading garbage values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2 \u2014 Parameterized constructor <\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Student {\nprivate:\n    int a;\npublic:\n    int b;\n\n    \/\/ Parameterized constructor: caller chooses values\n    Student(int m, int n) {\n            a=m;\n            b=n;\n      }\n\n    void display() const {\n        cout &lt;&lt; \"The value of a and b is: \" &lt;&lt; a &lt;&lt; \" and \" &lt;&lt; b &lt;&lt; '\\n';\n    }\n};\n\nint main() {\n    Student s(5, 10);  \n    s.display();\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p><strong>What to notice:<\/strong> the object starts in a meaningful state chosen by the caller. Initializer lists are especially important for <code>const<\/code> members, references, or complex objects.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3 \u2014 Constructor overloading <\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\n#include &lt;stdexcept&gt;\nusing namespace std;\n\nclass Student {\nprivate:\n    int a;\npublic:\n    int b;\n\n    \/\/ 1) Default\n    Student(){\n             a=0;\n             b=0 \n        }\n\n    \/\/ 2) One-arg (delegates to two-arg)\n      Student(int m) {\n            a=m;\n       }\n\n    \/\/ 3) Two-arg with validation\n      Student(int m, int n) {\n            a=m;\n            b=n;\n      }\n\n    void display() const {\n        cout &lt;&lt; \"The value of a and b is: \" &lt;&lt; a &lt;&lt; \" and \" &lt;&lt; b &lt;&lt; '\\n';\n    }\n};\n\nint main() {\n    Student s1;        \/\/ (0,0)\n    Student s2(7);     \/\/ (7,0)\n    Student s3(5, 10); \/\/ (5,10)\n    s1.display();\n    s2.display();\n    s3.display();\n}\n<\/code><\/pre>\n\n\n\n<p><strong>What to notice:<\/strong> you can provide several constructors so users of your class have <strong>clear, safe options<\/strong>. Delegating constructors help keep logic in one place.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Default vs parameterized <\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Feature<\/th><th>Default constructor<\/th><th>Parameterized constructor<\/th><\/tr><\/thead><tbody><tr><td>Arguments<\/td><td>None<\/td><td>One or more<\/td><\/tr><tr><td>Initialization<\/td><td>Safe baseline (e.g., zeros)<\/td><td>Caller chooses values<\/td><\/tr><tr><td>Flexibility<\/td><td>Same defaults for all objects<\/td><td>Each object can be different<\/td><\/tr><tr><td>Example<\/td><td>  Student(){<br>             a=0;<br>             b=0 <br>        }<\/td><td>  Student(int m, int n) {<br>            a=m;<br>            b=n;<br>      }<\/td><\/tr><tr><td>Call site<\/td><td><code>Student s;<\/code><\/td><td><code>Student s(5,10);<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Destructors in C++<\/h2>\n\n\n\n<p>C++ also runs a special function at the end of an object\u2019s life so that resources are released safely even if you forget to do it manually.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>A destructor in C++ is a special member function with the same name as the class prefixed by <code>~<\/code>, has no return type and no parameters, and is invoked automatically when an object goes out of scope or is deleted to perform cleanup (e.g., free memory, close files, release handles).<\/p>\n<\/blockquote>\n\n\n\n<p>Destructors exist to <strong>prevent leaks or misuse of resources<\/strong>. They\u2019re essential when your class acquires ownership of something that lives outside normal variables\u2014heap memory (<code>new<\/code>\/<code>new[]<\/code>), file descriptors, sockets, mutexes, database connections, etc. You write at most one destructor per class, and you <strong>don\u2019t<\/strong> overload it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Syntax and core rules (quick reference)<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ClassName {\npublic:\n    ~ClassName();   \/\/ declaration\n};\n\nClassName::~ClassName() {\n    \/\/ cleanup code here\n}\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No parameters, no return type, <strong>no overloading<\/strong>.<\/li>\n\n\n\n<li>Called automatically on scope exit, or when you <code>delete<\/code>\/<code>delete[]<\/code> a dynamically allocated object.<\/li>\n\n\n\n<li>Destruction order is the <strong>reverse<\/strong> of construction: members are destroyed first (in declaration order), then the object itself.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4 \u2014 Seeing the destructor run <\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Marker {\npublic:\n    Marker()  { cout &lt;&lt; \"Marker constructed\\n\"; }\n    ~Marker() { cout &lt;&lt; \"Marker destroyed\\n\";   }\n};\n\nint main() {\n    cout &lt;&lt; \"Entering scope\\n\";\n    {\n        Marker m;    \/\/ constructor runs here\n        cout &lt;&lt; \"Using m inside scope\\n\";\n    }               \/\/ destructor runs automatically here\n    cout &lt;&lt; \"After scope\\n\";\n}\n<\/code><\/pre>\n\n\n\n<p><strong>What to notice:<\/strong> the destructor is guaranteed to run when <code>m<\/code> leaves scope\u2014even if you <code>return<\/code> early or an exception is thrown\u2014making scope a <strong>safety net<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Constructor vs Destructor (quick comparison)<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Aspect<\/th><th>Constructor<\/th><th>Destructor<\/th><\/tr><\/thead><tbody><tr><td>Purpose<\/td><td>Initialize object state<\/td><td>Release resources \/ cleanup<\/td><\/tr><tr><td>Name<\/td><td>Same as class<\/td><td><code>~<\/code> + class name<\/td><\/tr><tr><td>Parameters<\/td><td>Allowed (overloading supported)<\/td><td>Not allowed (no overloading)<\/td><\/tr><tr><td>When called<\/td><td>At object creation<\/td><td>When object goes out of scope \/ is deleted<\/td><\/tr><tr><td>Count per class<\/td><td>Many (overloads)<\/td><td>One<\/td><\/tr><tr><td>Provided by compiler<\/td><td>Yes (defaulted if none defined)<\/td><td>Yes (defaulted if none defined)<\/td><\/tr><tr><td>Typical duties<\/td><td>Set defaults, enforce invariants, accept args<\/td><td>Free memory, close files\/sockets, release locks<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>Constructors give objects a <strong>correct beginning<\/strong>; destructors give them a <strong>safe ending<\/strong>. Use default and parameterized constructors to make creation both safe and convenient, and overload when you want multiple valid ways to build the same class. When your class owns resources, lean on RAII and let the destructor guarantee cleanup, even across errors and early returns. This is the foundation of reliable, modern C++ class design.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ gives every object a clear life story: it\u2019s created, used, and then destroyed. To make this safe and predictable, the language runs a special function at birth (to initialize the object) and another at death (to clean up resources). Constructors in C++ Constructors exist to prevent uninitialized state, to let callers pass meaningful values at creation time, and to centralize setup logic in one place. In practice, you\u2019ll use two common kinds; You may define multiple constructors for the&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/01\/29\/understanding-constructors-in-c\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":5087,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"enabled":false},"version":2}},"categories":[351,637],"tags":[718,603],"class_list":["post-4799","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-courses","category-oop-with-c","tag-constructor-in-c","tag-oop"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2024\/11\/CONSTRUCTOR.png?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-1fp","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4799","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/comments?post=4799"}],"version-history":[{"count":28,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4799\/revisions"}],"predecessor-version":[{"id":42861,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/4799\/revisions\/42861"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/5087"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=4799"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=4799"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=4799"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}