C++ Programming - OOPS Concepts - Discussion

Discussion :: OOPS Concepts - General Questions (Q.No.31)


Which of the following is the correct way of declaring a function as constant?

[A]. const int ShowData(void) { /* statements */ }
[B]. int const ShowData(void) { /* statements */ }
[C]. int ShowData(void) const { /* statements */ }
[D]. Both A and B

Answer: Option C


No answer description available for this question.

Durgam_Anil said: (Aug 28, 2012)  
Speciality of the c++;.

In general c, we will write the const first the function name but in the c++.

//return type then after that function name then const.

Neel Desai said: (Sep 22, 2012)  
Can you give one example ?

Deepak Kumar said: (Nov 19, 2012)  
// constant_member_function.cpp
class Date
Date( int mn, int dy, int yr );
int getMonth() const; // A read-only function
void setMonth( int mn ); // A write function; can't be const
int month;

int Date::getMonth() const
return month; // Doesn't modify anything
void Date::setMonth( int mn )
month = mn; // Modifies data member
int main()
Date MyDate( 7, 4, 1998 );
const Date BirthDate( 1, 18, 1953 );
MyDate.setMonth( 4 ); // Okay
BirthDate.getMonth(); // Okay
BirthDate.setMonth( 4 ); // C2662 Error

Nazmul said: (May 3, 2013)  
Is this ok that a const object can refer to/call only a const function?

Navnath Dombale said: (Dec 14, 2014)  
During object creation is there need to write const keyword like const date bdate();

Govind Kawde said: (Jul 13, 2017)  
Yes, I too think option D is Correct.

Sudeshna Cnaudhuri said: (Sep 5, 2017)  
C is the wrong option. I checked it by running a program in Dev c++.

Both A and B works. D is the correct one.

Chuck N said: (May 15, 2018)  
Exampe C is correct.

Examples A and B compile,but it seems the const keyword is just ignored, the function does NOT actually work as const. Below is a different example I found elsewhere. Since non-const functions can only be called by non-const objects, the below example will only compile if the function getValue is declared as in the example C.

If declared as in examples A and B, you will get a compiler error. The compiler error will go away if " Test t" in Main is not declared as a const, BUT the compiler is just ignoring the const keyword and the function is NOT const in these cases.

#include <iostream>
using namespace std;

class Test {
int value;
Test(int v = 0) {value = v;}
int getValue() const {return value;}

int main() {
const Test t;
cout << t.getValue();
return 0;

Waqar Akram said: (Mar 8, 2020)  
Option C is Correct.
Example of Deepak Kumar is 100% correct.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.