Overloading a function in C++

M

Marko.Cain.23

Why the following code compiles in C++, it is overloading a funciton
"x" with 2 different return value (one is int, one is void). Is that
legal? Thanks.

class Test1
{
public:
Test1();
virtual ~Test1();

int x() { return _x;}
void x(int x1) { _x = x1;}

private:
int _x;
};
 
S

Sharad Kala

| Why the following code compiles in C++, it is overloading a funciton
| "x" with 2 different return value (one is int, one is void). Is that
| legal? Thanks.

You are mistaken. It is not overloading on the return value, in fact you
can't overload on the return value.

| class Test1
| {
| public:
| Test1();
| virtual ~Test1();
|
| int x() { return _x;}

This takes void as parameter and returns int

| void x(int x1) { _x = x1;}

This takes int as parameter and returns void

|
| private:
| int _x;
| };

Sharad
 
J

Jim Langston

Why the following code compiles in C++, it is overloading a funciton
"x" with 2 different return value (one is int, one is void). Is that
legal? Thanks.

class Test1
{
public:
Test1();
virtual ~Test1();

int x() { return _x;}
void x(int x1) { _x = x1;}

private:
int _x;
};

As long as the parameters are different, and in this case one is void and
one is int, it is legal.
 
M

Marco Wahl

class Test1
{
public:
Test1();
virtual ~Test1();

int x() { return _x;}
void x(int x1) { _x = x1;}

private:
int _x;
};
[...] Is that legal?

Yes.

Just to make it clear. The following class is illegal in C++.

[[[
/**
This code will not compile.

Cause: Two function-declarations that differ only in the
return-type.
*/
class Test2
{
public:
int x();
void x();
};
]]]

Different return-types can not be used for overloading functions in
C++. Overloading is based on the arguments of functions.
 
T

Tim Slattery

Why the following code compiles in C++, it is overloading a funciton
"x" with 2 different return value (one is int, one is void). Is that
legal? Thanks.
int x() { return _x;}
void x(int x1) { _x = x1;}

They can't differ *only* by return type. Since these two functions
have different argument lists, your code will work fine.

--
Tim Slattery
(e-mail address removed)
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top