Home » C++ programs » C++ Class and Objects programs

Const Member Functions in C++

C++ | Const Member Functions: Here, we are going to learn how to declare constant (const) member functions in C++?
Submitted by IncludeHelp, on September 20, 2018

C++ Const Member Functions

A constant (const) member function can be declared by using const keyword, it is used when we want a function that should not be used to change the value of the data members i.e. any type of modification is not allowed with the constant member function.


Here, we have a class named "Numbers" with two private data members a and b and 4 member functions two are used as setter functions to set the value of a and b and 2 are constant members functions which are using as getter functions to get the value of a and b.


#include <iostream>
using namespace std;

class Numbers
        int a;
        int b;
        Numbers() {a = 0; b = 0;}
        //setter functions to set a and b
        void set_a(int num1)
            a = num1;
        void set_b(int num2)
            b = num2;
        //getter functions to get value of a and b
        int get_a(void) const
            return a;
        int get_b(void) const
            return b;

//Main function
int main()
    //declaring object to the class
    Numbers Num;
    //set values
    //printing values
    cout<<"Value of a: "<<Num.get_a()<<endl;
    cout<<"Value of b: "<<Num.get_b()<<endl;
    return 0;


Value of a: 100
Value of b: 200


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.