resolving of return types

K

kmw

Hello,

consider the following code snippet. I do not understand why the
compiler is not able to choose the correct variation of the method get
():
test.cpp: In function ‘int main()’:
test.cpp:31: error: conversion from ‘B’ to non-scalar type ‘C’
requested

What is the difference to the std::vector example? Isn't begin ()
defined as below?

iterator begin();
const_iterator begin() const;()

Any comments are appreciated.
Best regards,
Kay

#include <vector>
class B
{
};
class C
{
};
class A
{
public:
B get ( )
{
B ret;
return ret;
}
C get ( ) const
{
C ret;
return ret;
}
};
int main ( )
{
// this works
std::vector<int> test_vector;
std::vector<int>::const_iterator it = test_vector.begin ();
std::vector<int>::iterator it2 = test_vector.begin ();
// but this not
A test_a;
B test_b = test_a.get ();
C test_c = test_a.get ();
return 0;
}
 
V

Victor Bazarov

kmw said:
Hello,

consider the following code snippet. I do not understand why the
compiler is not able to choose the correct variation of the method get
():
test.cpp: In function ‘int main()’:
test.cpp:31: error: conversion from ‘B’ to non-scalar type ‘C’
requested

What is the difference to the std::vector example? Isn't begin ()
defined as below?

iterator begin();
const_iterator begin() const;()

Well, yes, without the last parentheses, of course. :) But what is
'iterator' and 'const_iterator', and what's the relationship between them?
Any comments are appreciated.
Best regards,
Kay

#include <vector>
class B
{
};
class C
{
};
class A
{
public:
B get ( )
{
B ret;
return ret;
}
C get ( ) const
{
C ret;
return ret;
}
};
int main ( )
{
// this works
std::vector<int> test_vector;
std::vector<int>::const_iterator it = test_vector.begin ();
std::vector<int>::iterator it2 = test_vector.begin ();
// but this not
A test_a;
B test_b = test_a.get ();
C test_c = test_a.get ();
return 0;
}

The answer is simple: the 'const_iterator' implemented in 'std::vector'
can be initialized from a regular 'iterator'. The first time you call
'begin()' (when initializing 'it'), it returns a regular iterator, and
calls the regular 'begin()', not a const one. Then 'it' is initialized
from the regular iterator. Add a c-tor in 'C' to initialize it from a
'B', and you're going to be OK:

class C { public: C(); C(B); };

V
 

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

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top