C++ Programming - OOPS Concepts - Discussion

Discussion Forum : OOPS Concepts - General Questions (Q.No. 31)
31.
Which of the following is the correct way of declaring a function as constant?
const int ShowData(void) { /* statements */ }
int const ShowData(void) { /* statements */ }
int ShowData(void) const { /* statements */ }
Both A and B
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
13 comments Page 1 of 2.

Durgam_anil said:   1 decade ago
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:   1 decade ago
Can you give one example ?

Deepak Kumar said:   1 decade ago
// constant_member_function.cpp
class Date
{
public:
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
private:
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
}
(3)

Nazmul said:   1 decade ago
Is this ok that a const object can refer to/call only a const function?

Navnath Dombale said:   1 decade ago
During object creation is there need to write const keyword like const date bdate();

Govind kawde said:   8 years ago
Yes, I too think option D is Correct.

Sudeshna cnaudhuri said:   8 years ago
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:   7 years ago
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;
public:
Test(int v = 0) {value = v;}
int getValue() const {return value;}
};

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

Waqar Akram said:   5 years ago
Option C is Correct.
Example of Deepak Kumar is 100% correct.

Sai Aditya said:   4 years ago
I think option D is the right one.


Post your comments here:

Your comments will be displayed after verification.