aeipownu
aeipownu

Reputation: 107

Not sure what a constant function is in c++

The assignment is to create a constant function getArea() that returns the area of a rectangle.

double getArea() {
    return width * height;
}

Is this it?

Do I put const after the parameters?

I don't really understand what I'm being asked.

Upvotes: 3

Views: 2922

Answers (4)

Ajay
Ajay

Reputation: 18461

Consider:

class ClassType
{
int x;
public:
ClassType(int _x) : x(_x) {}

int GetX() { return x;}
};

const ClassType object(20);
object.GetX();

This will fail to compile, since the object is const (readonly). But GetX is not marked const (readonly). length(), size(), IsOpen() are example of methods that may be called from a read only object. Hence the class should facilitate such (const) functions for const object.

You generally don't create const object, but you do pass them like:

void foo(const ClassType& obj);

Therefore, the GetX function should be:

int GetX() const { return x;}

const make a promise or a contract that this function doesn't modify this object.

Upvotes: 2

Bullionist
Bullionist

Reputation: 2210

double getArea() const 
   {
     return width * height;
   }

const keyword is used when the user doesnt want to modify or change the values of that variable or function.

Upvotes: 3

ShahiM
ShahiM

Reputation: 3268

Just like the built-in data types (int, double, char, etc…), class objects can be made const by using the const keyword. All const variables must be initialized at time of creation.

Once a const class object has been initialized via constructor, any attempt to modify the member variables of the object is disallowed, as it would violate the constness of the object. This includes both changing member variables directly (if they are public), or calling member functions that sets the value of member variables.

const class objects can only call const member functions. A const member function is a member function that guarantees it will not change any class variables or call any non-const member functions.

SOURCE : leancpp.com

Upvotes: 2

Reena Upadhyay
Reena Upadhyay

Reputation: 2017

In C++, a function becomes const when const keyword is used in function’s declaration. The idea of const functions is not allow them to modify the object on which they are called.

double getArea() const    {
    return width * height;
}

const after the (empty) argument list in the function declarations. indicates that getArea() function do not modify the state of a object i.e. data member of a object.

Please refer this link for more explanation: http://www.codeproject.com/Articles/389602/Constant-Member-Functions-Are-Not-Always-Constant

Upvotes: 6

Related Questions