I have a question related to function.

fun(const int);<-- pass a const int
const int fun(int);<--return a const int

but what is "fun(int) const"?

Recommended Answers

All 8 Replies

so if the function looks like this "fun(classA A) const", only const classA object can pass to this function?

No, I think it means that the object from which the const function is being called will not be changed. Using your example function (a method of the classA class)

classA A;
  classA B;

  A.fun( B );

guarantees that object A will not be changed by the actions of the function.

No. It means that foo() can not change any class values

class A
{
public:
    A() {m_x = 0;}
    int GetX() {return m_x;}
    int foo(A& obj) const;
protected:
    int m_x;
};

int A::foo(A& obj) const
{
    m_x = 2; // <<<<<< THIS IS ILLEGAL
    return obj.GetX();
}

int main()
{
    A obj;
    obj.foo(obj);

    return 0;
}

how about local variable or globle variable? Can them be changed?

I have another question.say if there is another class function "int foo(A& obj);", when does it be called? how does it distiguish with that const function?

any clue?

provided that there is a const keyword after the entire function declaration, then, it cannot change any value in memory. It will just use a copy of the value.
Now, int foo(int & a); is used if you want to modify the value of an extenal data element. It is called passing by reference. So this means that using the const keyword is the exact opposite for for using the "&" (ampersand). Try this link:http://cplusplus.com/doc/tutorial/functions2.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.