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?
Discussion:
13 comments Page 2 of 2.
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
}
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)
Neel desai said:
1 decade ago
Can you give one example ?
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.
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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers