Re: Problem with temporary object instantiation
- From: "Nikolaos D. Bougalis" <nikb@xxxxxxxxxxxxx>
- Date: Sun, 29 Jan 2006 01:49:59 -0800
Chris Yoedhana wrote:
> Hi,
>
> I cannot figure out why this code fails to compile. I use 2 files, main.h
> and main.cpp to separate class declaration and definition.
>
> in main.h
>
> #define MAIN_H
>
> #include <iostream>
>
> class TestClass {
> public:
> TestClass(int val);
> TestClass(float, int);
> };
>
> class WrapperClass {
> public:
> WrapperClass(const TestClass& testa);
> int j;
> };
> #endif
>
> in main.cpp
>
> #include "main.h"
>
> TestClass::TestClass(float a, int b)
> {
> std::cout<<"Invoking test class ctor with 2 param\n";
> }
>
> TestClass::TestClass(int val)
> {
> std::cout<<"TestClass val = "<<val<<std::endl;
> }
>
> WrapperClass::WrapperClass(const TestClass &aTest):j(0)
> {
> std::cout<<"Calling wrapper class constructor\n";
> }
>
> int main()
> {
> int i;
> WrapperClass wrapper0(TestClass(i));
> std::cout<<"wrapper0.j = "<<wrapper0.j<<std::endl;
> return 0;
> }
>
> The error message is:
> main.cpp(22) : error C2228: left of '.j' must have class/struct/union type
> type is 'overloaded-function'
Visual C++ is correctly flagging an error here, because the statement
"WrapperClass wrapper0(TestClass(i));" declares a function named
"wrapper0" which takes a parameter of type "TestClass" named "i" and
returns to its caller an object of type "WrapperClass."
You can convince yourself of that by adding the following code in your
main():
WrapperClass wrapper1(TestClass(i));
TestClass ti(444);
WrapperClass wc = wrapper1(ti);
If you compile, you will see that the new code does not produce an
error, unless you try to link, since no implementation is provided for
wrapper1.
It's a bit obscure, granted. It happens because your code is ambiguous,
forcing the compiler to interpet the statement as a declaration, as
required in section 8.2 of the standard.
> I can make the code compile by doing the following :
> 1. Replace i with an integer constant
> WrapperClass wrapper0(TestClass(i)) --> WrapperClass
> wrapper0(TestClass(100))
Yes, because that statement is not ambiguous (and thus doesn't have to
be resolved in favor of a declaration) because 'i' can be the name of a
parameter, but 100 cannot since names of parameters may not start with a
digit.
I hope this helps,
Nik B.
.
- References:
- Problem with temporary object instantiation
- From: Chris Yoedhana
- Problem with temporary object instantiation
- Prev by Date: Problem with temporary object instantiation
- Next by Date: installation of asp.net project
- Previous by thread: Problem with temporary object instantiation
- Next by thread: installation of asp.net project
- Index(es):
Relevant Pages
|