{"id":8378,"date":"2025-09-29T07:33:49","date_gmt":"2025-09-29T02:33:49","guid":{"rendered":"https:\/\/afzalbadshah.com\/?p=8378"},"modified":"2025-09-29T07:33:51","modified_gmt":"2025-09-29T02:33:51","slug":"constants-in-oop-c","status":"publish","type":"post","link":"https:\/\/afzalbadshah.com\/index.php\/2025\/09\/29\/constants-in-oop-c\/","title":{"rendered":"Constants in OOP &#8211; C++"},"content":{"rendered":"\n<p>In our daily life, there are some values that <strong>never change<\/strong>. For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <strong>number of days in a week<\/strong> is always 7.<\/li>\n\n\n\n<li>The <strong>speed of light<\/strong> in a vacuum is constant.<\/li>\n\n\n\n<li>A <strong>student\u2019s roll number<\/strong> assigned once in a class does not change.<\/li>\n<\/ul>\n\n\n\n<p>These values remain fixed regardless of circumstances. Similarly, in C++, if we want to create a variable whose value should <strong>not be altered during the program execution<\/strong>, we declare it as <strong>constant<\/strong> using the <code>const<\/code> keyword. <a href=\"https:\/\/afzalbadshah.com\/index.php\/object-oriented-programming-in-c-a-comprehensive-tutorial\/\" target=\"_blank\" rel=\"noopener\" title=\"\">The detailed tutorial can be visited here. <\/a><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>A constant in C++ is a variable whose value cannot be modified after initialization.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">Why Do We Need Constants?<\/h2>\n\n\n\n<p>Constants are essential because they represent <strong>fixed values<\/strong> and prevent accidental modifications.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Data Safety:<\/strong> Ensures values do not change mistakenly during program execution.<\/li>\n\n\n\n<li><strong>Readability:<\/strong> Makes the code clearer by indicating that a value is fixed.<\/li>\n\n\n\n<li><strong>Maintainability:<\/strong> If a constant changes in the future (e.g., tax rate), we only update it in one place.<\/li>\n\n\n\n<li><strong>Reliability:<\/strong> Prevents bugs that may occur due to unintended modification of important values.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Declaring Constants<\/h2>\n\n\n\n<p>In C++, constants can be declared using the <code>const<\/code> keyword.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const int daysInWeek = 7;\nconst float PI = 3.14159;\n<\/code><\/pre>\n\n\n\n<p>Once declared, their values cannot be changed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Example 1: Basic Constant Usage<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint main() {\n    const float PI = 3.14159;   \/\/ Constant declaration\n    float radius = 5;\n\n    float area = PI * radius * radius;\n    cout &lt;&lt; \"Area of circle = \" &lt;&lt; area &lt;&lt; endl;\n\n    \/\/ PI = 3.14;   \/\/ \u274c Error: cannot modify a const variable\n\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Area of circle = 78.5397\n<\/code><\/pre>\n\n\n\n<p>Here, <code>PI<\/code> remains fixed throughout the program.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Constants in Classes<\/h2>\n\n\n\n<p>We can also use constants inside classes. They are useful for defining values that are common for all objects but should not change, like maximum marks or fixed tax rates.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Student {\npublic:\n    const int rollNumber;   \/\/ constant data member\n\n    Student(int r)  {\n      rollNumber = r;\/\/ Initialization using constructor\n    }\n\n    void show() {\n        cout &lt;&lt; \"Roll Number: \" &lt;&lt; rollNumber &lt;&lt; endl;\n    }\n};\n\nint main() {\n    Student s1(101);\n    Student s2(102);\n\n    s1.show();\n    s2.show();\n    return 0;\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Roll Number: 101\nRoll Number: 102\n<\/code><\/pre>\n\n\n\n<p>Here, <code>rollNumber<\/code> is constant\u2014once assigned through the constructor, it cannot change.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Const Member Functions<\/h2>\n\n\n\n<p>A member function can also be declared as <code>const<\/code>.<br>This means it cannot modify any member variables of the class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Demo {\n    int value;\npublic:\n    Demo(int v) {\n      value = v;\n    }\n\n    int getValue() const {   \/\/ const function\n        return value;\n    }\n};\n<\/code><\/pre>\n\n\n\n<p>If you try to change <code>value<\/code> inside <code>getValue()<\/code>, the compiler will give an error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Pointers and Constants<\/h2>\n\n\n\n<p>Constants can also be used with pointers in three different ways. To make it simple, think of a <strong>pointer<\/strong> as an arrow that shows the address of a variable, while <strong>const<\/strong> controls whether the arrow itself can move or whether the value it points to can change.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Pointer to Constant Data<\/strong><br>Here the data is fixed, but the pointer can point somewhere else.<br>Daily life example: You have a <em>book<\/em> that you can only read but not edit. However, you can put down this book and pick up another. <code>const int x = 10; const int* ptr = &amp;x; \/\/ data is constant, pointer can change<\/code><\/li>\n\n\n\n<li><strong>Constant Pointer<\/strong><br>Here the pointer cannot move to another address, but the data at that location can still change.<br>Daily life example: Imagine you are tied to a single chair. You cannot move to another chair, but you can still adjust the cushion on your chair. <code>int y = 20; int* const ptr2 = &amp;y; \/\/ pointer is constant, data can change<\/code><\/li>\n\n\n\n<li><strong>Constant Pointer to Constant Data<\/strong><br>Here both the pointer and the data are fixed.<br>Daily life example: You are tied to a chair, and the cushion on that chair is also locked\u2014you can neither move to another chair nor adjust the cushion. <code>const int z = 30; const int* const ptr3 = &amp;z; \/\/ both pointer and data are constant<\/code><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Daily Life Example<\/h2>\n\n\n\n<p>Think of <strong>days in a week<\/strong>.<br>No matter where you live, you always have 7 days in a week.<br>This is just like a constant variable: it is <strong>defined once and never changes<\/strong>.<\/p>\n\n\n\n<p>Or consider a <strong>roll number<\/strong> in a classroom\u2014assigned once and fixed for the student.<br>That\u2019s how constants work in C++.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Comparison: Normal vs Constant vs Static Members<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Aspect<\/th><th>Normal Variable<\/th><th>Constant Variable<\/th><th>Static Variable<\/th><\/tr><\/thead><tbody><tr><td>Value<\/td><td>Can change anytime<\/td><td>Fixed, cannot be modified<\/td><td>Shared among all objects<\/td><\/tr><tr><td>Initialization<\/td><td>Can be later<\/td><td>Must be at declaration\/constructor<\/td><td>Declared once, defined outside class<\/td><\/tr><tr><td>Usage<\/td><td>For dynamic values<\/td><td>For fixed values<\/td><td>For shared\/persistent values<\/td><\/tr><tr><td>Safety<\/td><td>Risk of accidental changes<\/td><td>Protected against changes<\/td><td>Prevents duplication, ensures persistence<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Constants ensure stability and prevent accidental modification.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Exercises<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Write a program that uses a constant <code>PI<\/code> to calculate the area of a circle.<\/li>\n\n\n\n<li>Create a class with a constant roll number that is initialized via constructor.<\/li>\n\n\n\n<li>Write a program to demonstrate a constant pointer to constant data.<\/li>\n\n\n\n<li>Make a constant member function that returns the value of a private variable.<\/li>\n<\/ol>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In our daily life, there are some values that never change. For example: These values remain fixed regardless of circumstances. Similarly, in C++, if we want to create a variable whose value should not be altered during the program execution, we declare it as constant using the const keyword. The detailed tutorial can be visited here. A constant in C++ is a variable whose value cannot be modified after initialization. Why Do We Need Constants? Constants are essential because they&#8230;<\/p>\n<p class=\"read-more\"><a class=\"btn btn-default\" href=\"https:\/\/afzalbadshah.com\/index.php\/2025\/09\/29\/constants-in-oop-c\/\"> Read More<span class=\"screen-reader-text\">  Read More<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":8384,"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,721,720,603],"class_list":["post-8378","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oop-with-c","tag-c","tag-constant","tag-constant-in-c","tag-oop"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/afzalbadshah.com\/wp-content\/uploads\/2025\/09\/Access-Modifers-in-OOP-Java.jpg?fit=1920%2C1080&ssl=1","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pf3emP-2b8","jetpack-related-posts":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/8378","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=8378"}],"version-history":[{"count":5,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/8378\/revisions"}],"predecessor-version":[{"id":8400,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/posts\/8378\/revisions\/8400"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media\/8384"}],"wp:attachment":[{"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/media?parent=8378"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/categories?post=8378"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/afzalbadshah.com\/index.php\/wp-json\/wp\/v2\/tags?post=8378"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}