Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-declaring a function in C++ class

Tags:

c++

class arbit
    {
        int var;
        public:

        int method1();
        int method1() const;

    };

Why does g++ does not give warning while declaring the same function twice here ?

like image 432
Amit Avatar asked Aug 09 '10 19:08

Amit


People also ask

How do you declare a function in C?

Function Declarations The actual body of the function can be defined separately. int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

What is the correct way of declaring a function?

1. Function declaration. A function declaration is made of function keyword, followed by an obligatory function name, a list of parameters in a pair of parenthesis (para1, ..., paramN) and a pair of curly braces {...} that delimits the body code.

When should you declare a function in C language?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.

What is function declaration and definition in C?

A function consist of two parts: Declaration: the function's name, return type, and parameters (if any) Definition: the body of the function (code to be executed)


1 Answers

Because one is const and the other is not. These are different overloads, with different signatures. One or the other gets called, depending on whether the object you call it on is const.

Example:

arbit x;
x.method1(); // calls the non-const version
arbit const &y = x;
y.method1(); // calls the const version

You should declare a method as const if it doesn't modify the (visible) state of the object. That allows you to hand out const arbit objects, and be certain¹ that someone won't accidentally modify them.

For example, you would make a function setValue non-const (because it modifies the object), but getValue would be const. So on a const object, you could call getValue but not setValue.


¹ When there's a will, there's a way, and it's called const_cast. But forget that I ever told you.

like image 97
Thomas Avatar answered Oct 28 '22 16:10

Thomas