nested instantiation

This passes a nose to a Face constructor:
1
2
NoseElephant nose1(3);
Face face1(nose1);


Is there a way to do the same with an anonymous nose?
This did not work:
 
Face face2(NoseElephant(3));


Here is the complete code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Nose
{
};

class NoseElephant : public Nose
{
    private:
        int size;
    public:
        NoseElephant(int s): size(s) {}
};

class Face
{
    private:
        Nose& nose;
    public:
        Face(Nose& n): nose(n) {}
};

int main()
{
    NoseElephant nose1(3);
    Face face1(nose1);          //this compiles

    Face face2(NoseElephant(3));//error
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
C:\C++\demo_MinGW>g++ anonymous.cpp
anonymous.cpp: In function 'int main()':
anonymous.cpp:28:31: error: no matching function for call to 'Face::Face(NoseEle
phant)'
     Face face2(NoseElephant(3));
                               ^
anonymous.cpp:28:31: note: candidates are:
anonymous.cpp:20:9: note: Face::Face(Nose&)
         Face(Nose& n): nose(n) {}
         ^
anonymous.cpp:20:9: note:   no known conversion for argument 1 from 'NoseElephan
t' to 'Nose&'
anonymous.cpp:15:7: note: Face::Face(const Face&)
 class Face
       ^
anonymous.cpp:15:7: note:   no known conversion for argument 1 from 'NoseElephan
t' to 'const Face&'


A similar program without the size parameter compiles without error:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Nose
{
};

class NoseElephant : public Nose
{
};

class Face
{
    private:
        Nose& nose;
    public:
        Face(Nose& n): nose(n) {}
};

int main()
{
    NoseElephant nose1;
    Face face1(nose1);        //this compiles

    Face face2(NoseElephant); //this compiles
}

Thank you.
Last edited on
Line 22 compiles because it is not constructing; it is declaring a function called face2 that takes a NoseElephant as a parameter and returns a Face.

You can't do it with an anonymous object because you are taking a reference. I'm not certain how I'd rewrite your program to make it work, though; did you have an objective in writing it?
Thanks Zhuge.

The reference is needed.
I was just thought anonymous instantiation would be a good way to tidy up some code.
Why does anonymous object not work with a reference?
An anonymous object (usually called temporary object) only lives until the end of the full-expression in which it appear. After line 26 the NoseElephant object no longer exist and Face would be left with an invalid reference. The reason it didn't compile at all is because temporary objects can't bind to non-const references.
Last edited on
Thank you for the explanation Peter87. That makes sense.
Topic archived. No new replies allowed.