{"id":42205,"date":"2025-01-22T09:05:00","date_gmt":"2025-01-22T04:05:00","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=42205"},"modified":"2026-02-17T17:32:37","modified_gmt":"2026-02-17T12:32:37","slug":"constructors-in-c-object-oriented-programming","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/01\/22\/constructors-in-c-object-oriented-programming\/","title":{"rendered":"Constructors in C++ (Object-Oriented Programming)"},"content":{"rendered":"\n<p>When we create an object in C++, we expect it to start in a valid and usable state. In real life, a student record is not useful unless the university has stored the student\u2019s name and roll number. Similarly, a car in a showroom is not meaningful unless it has a model and an engine number. In programming, the mechanism that ensures this proper initial state of an object is called a constructor.<\/p>\n\n\n\n<p>A constructor guarantees that as soon as an object is created, it is properly initialized and ready to be used.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> A special member function of a class that is automatically called\nwhen an object is created. Its main purpose is to initialize the object.\n<\/code><\/pre>\n\n\n\n<p>A constructor has the following characteristics:<\/p>\n\n\n\n<p>\u2022 It has the same name as the class.<\/p>\n\n\n\n<p>\u2022 It has no return type (not even void).<\/p>\n\n\n\n<p>\u2022 It executes automatically when an object is created.<\/p>\n\n\n\n<p>\u2022 It is mainly used to initialize data members of the class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Need for Constructors<\/h2>\n\n\n\n<p>In C++, when memory is allocated for an object, the data members may contain garbage values if they are not explicitly initialized. Using such uninitialized data can cause unpredictable behavior in programs.<\/p>\n\n\n\n<p>Consider a student management system. If a Student object is created without initializing the name and roll number, the system may display incorrect or meaningless information. Therefore, initialization at the time of object creation is essential.<\/p>\n\n\n\n<p>We can summarize this idea as:<\/p>\n\n\n\n<p><strong>Object Creation = Memory Allocation + Initialization<\/strong><\/p>\n\n\n\n<p>Constructors ensure that initialization happens immediately after memory allocation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Default Constructor<\/h2>\n\n\n\n<p>A default constructor is a constructor that does not take any parameters. It assigns default or safe values to the data members.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>A constructor that takes no parameters and initializes an object with default values.\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Student Class with Default Constructor<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Student {\npublic:\n    string name;\n    int rollNo;\n\n    Student() {\n        name = \"Unknown\";\n        rollNo = 0;\n    }\n\n    void display() {\n        cout &lt;&lt; \"Name: \" &lt;&lt; name &lt;&lt; endl;\n        cout &lt;&lt; \"Roll No: \" &lt;&lt; rollNo &lt;&lt; endl;\n    }\n};\n\nint main() {\n    Student s1;\n    s1.display();\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>When the statement <code>Student s1;<\/code> is executed, the constructor runs automatically and initializes the data members. As a result, the object is created in a consistent and predictable state.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Parameterized Constructor<\/h2>\n\n\n\n<p>In many situations, we want to initialize objects with specific values at the time of creation. For example, when registering a student, the university already knows the student\u2019s name and roll number.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>A constructor that accepts parameters to initialize an object with specific values.\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Student Class with Parameterized Constructor<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Student {\npublic:\n    string name;\n    int rollNo;\n\n    Student(string n, int r) {\n        name = n;\n        rollNo = r;\n    }\n\n    void display() {\n        cout &lt;&lt; \"Name: \" &lt;&lt; name &lt;&lt; \", Roll No: \" &lt;&lt; rollNo &lt;&lt; endl;\n    }\n};\n\nint main() {\n    Student s1(\"Ali\", 101);\n    Student s2(\"Sara\", 102);\n\n    s1.display();\n    s2.display();\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>In this example, each object is initialized with meaningful data at the time of creation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Constructor Overloading<\/h2>\n\n\n\n<p>A class may require multiple ways to create objects. For example, sometimes we may want to create a student with default values, and sometimes with complete information.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Defining multiple constructors in the same class\nwith different parameter lists.\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Overloaded Constructors<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Student {\npublic:\n    string name;\n    int rollNo;\n\n    Student() {\n        name = \"Unknown\";\n        rollNo = 0;\n    }\n\n    Student(string n, int r) {\n        name = n;\n        rollNo = r;\n    }\n};\n<\/code><\/pre>\n\n\n\n<p>Now objects can be created in two different ways:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Student s1;                \/\/ Default constructor\nStudent s2(\"Hassan\", 205); \/\/ Parameterized constructor\n<\/code><\/pre>\n\n\n\n<p>This improves flexibility and usability of the class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using the <code>this<\/code> Keyword in Constructors<\/h2>\n\n\n\n<p>Sometimes the parameter names are the same as the data member names. In such cases, the <code>this<\/code> pointer is used to refer to the current object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>A pointer that refers to the calling object of the class.\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class Student {\npublic:\n    string name;\n    int rollNo;\n\n    Student(string name, int rollNo) {\n        this-&gt;name = name;\n        this-&gt;rollNo = rollNo;\n    }\n};\n<\/code><\/pre>\n\n\n\n<p>Here, <code>this-&gt;name<\/code> refers to the data member of the class, while <code>name<\/code> refers to the constructor parameter.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Constructor and Encapsulation<\/h2>\n\n\n\n<p>In well-designed programs, data members are usually kept private. Constructors help initialize private data properly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Car Class with Private Data<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Car {\nprivate:\n    string model;\n    string engineNo;\n\npublic:\n    Car(string m, string e) {\n        model = m;\n        engineNo = e;\n    }\n\n    void display() {\n        cout &lt;&lt; \"Model: \" &lt;&lt; model &lt;&lt; endl;\n        cout &lt;&lt; \"Engine No: \" &lt;&lt; engineNo &lt;&lt; endl;\n    }\n};\n\nint main() {\n    Car c1(\"Toyota Corolla\", \"ENG12345\");\n    c1.display();\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>In this design, the constructor ensures that every Car object has valid model and engine number information at creation time.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Constructors in Inheritance<\/h2>\n\n\n\n<p>When inheritance is used, the constructor of the base (parent) class is executed before the constructor of the derived (child) class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Order of Constructor Execution:\nBase Class Constructor \u2192 Derived Class Constructor\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Vehicle {\npublic:\n    Vehicle() {\n        cout &lt;&lt; \"Vehicle constructor called\" &lt;&lt; endl;\n    }\n};\n\nclass Car : public Vehicle {\npublic:\n    Car() {\n        cout &lt;&lt; \"Car constructor called\" &lt;&lt; endl;\n    }\n};\n\nint main() {\n    Car c1;\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p>When the Car object is created, the Vehicle constructor executes first, followed by the Car constructor.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-rich is-provider-canva wp-block-embed-canva\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Constructors in OOP\" src=\"https:\/\/www.canva.com\/design\/DAGWbOXB9EA\/rASWo-19JgJAiYaOnp_Z_A\/view?embed&amp;meta\" height=\"360\" width=\"640\" style=\"border: none; border-radius: 8px; width: 640px; height: 360px;\" allowfullscreen=\"allowfullscreen\" allow=\"fullscreen\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When we create an object in C++, we expect it to start in a valid and usable state. In real life, a student record is not useful unless the university has stored the student\u2019s name and roll number. Similarly, a car in a showroom is not meaningful unless it has a model and an engine number. In programming, the mechanism that ensures this proper initial state of an object is called a constructor. A constructor guarantees that as soon as&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/01\/22\/constructors-in-c-object-oriented-programming\/\"> 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":[637],"tags":[704,741,603],"class_list":["post-42205","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oop-with-c","tag-c","tag-constructors","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-aYJ","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/42205","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=42205"}],"version-history":[{"count":1,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/42205\/revisions"}],"predecessor-version":[{"id":42206,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/42205\/revisions\/42206"}],"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=42205"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=42205"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=42205"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}