CONTANT

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 4

CONSTANT DATA MEMBER AND

MEMBER FUNCTION
Constant Declaration

•const - a C++ keyword used to declare an object as constant or used to


declare a constant parameter.

•A constant member cannot modify member variables. For example,


•void setX(int x) const { this->x = x; // ERROR! }

•A constant data member cannot be modified by any member function, but


can be initialized by the constructor using a special syntax called member
initializer.

•The constructor and destructor cannot be made constant, as they need to


initialize member variables. However, a constant object can invoke non-
constant constructor. The constant property begins after construction.
Constant Member Function
• const function is a "read-only" function that
does not modify the object for which it is called.

• Syntax int myfunction() const //declaration

• int myclass ::myfunction() const // Definition

• The const keyword is required in both the


declaration and the definition. A constant
member function cannot modify any data
members or call any member functions that
aren't constant.
• // 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
}

You might also like