Function prototype & implementation mismatch

N

News

Hi,

Should the following code compile without errors?

class test
{
public:
void display(const int x);
};

void test::display(int num)
{
}

void main()
{
test object;
object.display(10);
}

The function prototype in the class declaration differs from the
implementation as the argument is const in the declaration but not in the
implementation (or the other way round). I know that this is slightly
superfluous as the int is being passed by value anyway & so cannot be
altered in the display() function as a return value. However, there is
still a mismatch! If the argument to display is passed by reference rather
than by value i.e.

class test
{
public:
void display(const int & x);
};

void test::display(int & num)
{
}

void main()
{
test object;
object.display(10);
}

then a compiler error is generated.

I am using the Microsoft C++ compiler (VC++6 & VC++.NET). What do other
compilers do with the first code sample?

Simon
 
G

Gianni Mariani

News said:
Hi,

Should the following code compile without errors?

class test
{
public:
void display(const int x);
};

void test::display(int num)
{
}

void main()

main *must* return int
{
test object;
object.display(10);
}

As a reference point, this compiles without error in gcc 3.3.1 and gcc
3.4.0.
The function prototype in the class declaration differs from the
implementation as the argument is const in the declaration but not in the
implementation (or the other way round). I know that this is slightly
superfluous as the int is being passed by value anyway & so cannot be
altered in the display() function as a return value. However, there is
still a mismatch! If the argument to display is passed by reference rather
than by value i.e.

class test
{
public:
void display(const int & x);
};

void test::display(int & num)
{
}

void main()
{
test object;
object.display(10);
}

then a compiler error is generated.

gcc 3.4.0 also generates a compile error.
 
F

Fraser Ross

It makes no difference to the caller whether a value parameter is const or
not. This is why it compiles and why I take the advice to make declarations
of value parameters non const.

Fraser.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top