Do you have to declare a class object in order to pass values to a constructor?

When it comes to constructors, do you have to declare a class object in order to pass values to that constructor?

Just look at the program below to see what i mean.
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
28
29
30
31
32
33
34
#include <iostream>

using namespace std;

class Color
{
    string y;

public:

    Color (string x)
    {
        y = x;

        cout << y << "\n";
    }
};

int main ()
{
    string favoritecolor;

    cout << "What is your favorite color?" << "\n";
    getline (cin,favoritecolor);


    Color ("Why can't I pass a variable to the constructor?");   //what is the difference between this?

    Color favorite (favoritecolor); //and this?

    //what are the limits for each of the call statements?

}
Color ("Why can't I pass a variable to the constructor?"); is a cast-expression of type Color.
(Implicit conversion from const char* to std::string, explicit conversion from std::string to Colour).
It yields a prvalue ("pure" rvalue).


Color favorite (favoritecolor); is a declaration-statement for a variable with automatic storage duration.
After this declaration, the expression favorite is an lvalue of type Colour.

http://en.cppreference.com/w/cpp/language/value_category
Topic archived. No new replies allowed.