• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C++ » Classes » const Member Functions c++
Next →
← Prev

const Member Functions c++

By Dinesh Thakur

The const qualifier is used with the variables of basic data types to prevent them from being modified by the function. In a similar way, const qualifier can also be applied to member functions, member function arguments and the objects of a class.

We’ll be covering the following topics in this tutorial:

  • const Member Functions
  • const Member Function Arguments
  • canst Objects

const Member Functions

A const or a constant member function can only read or retrieve the data members of the calling object without modifying them. If such a member function attempts to modify any data member of the calling object, a compile-time error is generated.

The syntax for defining a const member function is

return_type function_name (parameter_list) const {

//body of the member function

}

To understand the concept of const member functions, consider the class weight. As the member function putdata () does not alter any data member of the calling objects, it can be declared as const. In addition, the sum_weight () member function simply adds the data members of the calling object and the object passed as argument without modifying the calling object, hence this function can also be declared as const. However, the function getdata () cannot be declared as const, as it assigns values to the data members of the calling object.

Example: Declaration and definition of const member functions

//Declaration of Const member functions inside the class
 void putdata() const;
 weight sum_weight (weight) const;
 //Definition of const member functions outside the class
 void weight: : putdata () const //display weight {
   //body of the function
}
  weight weight :: sum_weight (weight w2) const {
    // const member function
    // body of the function
    // gram=100; //Error: cannot modify const object
}
    //Calling const member functions inside the main() function
    w3=w1.sum_weight(w2) ;

Now, if the sum_weight () function ‘attempts to change the values of data members of object w1 (that is the calling object) within the function, a compile-time error Cannot modify a const object is raised.

const Member Function Arguments

A const member function cannot modify the values of data members of the calling object. However, it can alter the values of the data members of the objects passed by reference. Thus to prevent the member function from modifying the arguments passed to it by reference, the const qualifier can be used with member function arguments in both declaration and definition of the member function.

To understand the concept of const member function arguments, consider this example.

Example: A program to demonstrate const member function arguments

#include<iostream.h>

class weight {

    int kilogram;

    int gram;

    public: void getdata();

    void putdata() const;

    weight sum_weight(const weight&) const;

};

    void weight::getdata() {

        cout<<“/n Kilograms:”;

        cin>>kilogram;

        cout<<“Grams:”;

        cin>>gram;

}

       void weight :: putdata () const {

        cout<<kilogram<<” Kgs. and”<<gram<<” gros.\n”;

       }

      weight weight::sum_weight(const weight& w2) const {

          weight temp; temp.gram = gram + w2.gram;

          temp.kilogram = temp.gram/1000;

          temp.gram = temp.gram%1000;

          temp.kilogram += kilogram+w2.kilogram;

          return (temp) ;

      }

int main () {

     weight w1,w2 ,w3;

     cout<<“Enter weight in kilograms and grams\n”;

     cout<<“\n Enter weight #1” ;

      w3=w1.sum_weight (w2);

      w1.getdata();

      cout<<” \n Enter weight #2″ ;

      w2.getdata();

      cout<<“/n Weight #1 = “;

      w1.putdata();

      cout<<“Weight #2 = “;

      w2.putdata();

      cout<<“Total Weight = “;

      w3.putdata();

      w3.sum_weight(w1,w2);

      return 0;

}

In this example, the function sum_weight () as well as the argument w2 passed to it by reference are declared as const. Hence, if an attempt is made to alter any data of either w1 (the calling object) or w2 (object passed by reference), a compile-time error is generated.

canst Objects

Like member functions and member function arguments, the objects of a class can also be declared as const. An object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object. A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data members of const objects results in a compile-time error.

The syntax for declaring a const object is

const class_name object_name;

Whenever an object is declared as const, it needs to be initialized at the time of declaration. However, the object initialization while declaring is possible only with the help of constructors.

You’ll also like:

  1. Write A C++ Program To Declare Const Member Function And Attempt Any Operation Within It.
  2. c++ – Defining member functions inside or outside the class definition
  3. Write A C++ Program By Using Member Functions Outside The Body Of Class To Find Area Of Rectangle.
  4. Write A C++ Program For Public Fields And Member Functions.
  5. Write A C++ Program To Declare Private Member Function And Access It Using Public Member Function.
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C++ Tutorials

C++ Tutorials

  • C++ - Data Types
  • C++ - Operators Types
  • C++ - CPP Program Structure
  • C++ - Conditional Statements
  • C++ - Loop
  • C++ - do-While Loop
  • C++ - Control Statements
  • C++ - Tokens
  • C++ - Jump Statements
  • C++ - Expressions
  • C++ - Constants
  • C++ - Character Set
  • C++ - Iteration Statements
  • C++ - I/O Statements
  • C++ - String
  • C++ - Manipulators

C++ Operator

  • C++ - Input/Output Operator
  • C++ - Operator Overloading

C++ Functions

  • C++ - Functions
  • C++ - Member Functions
  • C++ - Returning Object from Function
  • C++ - Call by Value Vs Reference
  • C++ - Friend Function
  • C++ - Virtual Function
  • C++ - Inline Function
  • C++ - Static Data Members
  • C++ - Static Member Functions

C++ Array & Pointer

  • C++ - Array
  • C++ - Array of Objects
  • C++ - Arrays as Class Members
  • C++ - Vector
  • C++ - Pointer
  • C++ - 'this' Pointer

C++ Classes & Objects

  • C++ - Class
  • C++ - Program Structure With Classes
  • C++ - OOP’s
  • C++ - Objects as Function Arguments
  • C++ - Procedure Vs OOL
  • C++ - Object Vs Class
  • C++ - Creating Objects
  • C++ - Constructors
  • C++ - Copy Constructor
  • C++ - Constructor Overloading
  • C++ - Destructor
  • C++ - Polymorphism
  • C++ - Virtual Base Class
  • C++ - Encapsulation

C++ Inheritance

  • C++ - Inheritance
  • C++ - Multiple Inheritance
  • C++ - Hybrid Inheritance
  • C++ - Abstraction
  • C++ - Overloading

C++ Exception Handling

  • C++ - Exception Handling
  • C++ - Templates
  • C++ - Standard Template Library

C++ Data Structure

  • C++ - Link List

C++ Programs

  • C++ Program for Electricity Bill
  • C++ Program for Multiply Matrices
  • C++ Program for Arithmetic Operators
  • C++ Program For Matrices
  • C++ Program for Constructor
  • C++ Program Verify Number
  • C++ Program Array Of Structure
  • C++ Program to find Average Marks
  • C++ Program Add And Subtract Matrices
  • C++ Program Menu Driven
  • C++ Program To Simple Interest
  • C++ Program To Find Average
  • C++ program exit()
  • C++ Program Using Array Of Objects
  • C++ Program Private Member Function
  • C++ Program To Reverse A String
  • C++ Program to Operator Overloading

Other Links

  • C++ - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2023. All Rights Reserved.