Question

My professor gave the following code:

Main.cpp

#include "state.h"
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char const *argv[]){
    
    const int success = 0;
    string name;

    State x;
    
    State y = "s2"; // This doesn't compile
    State z = y;
    State* p = new State(z);

    x = *p;
    p->set_name("s3");
    delete p;
    x.get_name(name);

    std::cout << "Name of state x is " << name << std::endl;
    std::cout << "Total number of states is " << State::total_number_of_states() << std::endl;

    return success;
}

State.h

#ifndef STATE_H
#define STATE_H
#include <string>

using namespace std;


class State
{
private:
    string* name; // str pointer used for illustrative purposes
    static int number_of_states;

public:
    State();
    State(string state_name);
    State(const State& state); // Will basically be the copy constructor
    virtual ~State();
    State& operator=(const State& state); // Copy on equal
    void get_name(string& state_name) const; 
    void set_name(string state_name);
    static int total_number_of_states();
};
typedef State *State_pointer;

#endif

In g++ 4.8 on Ubuntu, I get the following error:

$ g++ example_main_1.cpp state.cpp
example_main_1.cpp: In function ‘int main(int, const char**)’:
example_main_1.cpp:14:12: error: conversion from ‘const char [3]’ to non-scalar type ‘State’ requested
  State y = "s2"; // This doesn't compile

I asked him about this in class, he said that this is valid C++ and that it should work. I've never seen this kind of class instantiation before, where it would have to convert from a string literal to a std::string then convert that to a State object.

My professor then went on to point out that there are other equivalent invocations that are extremely close:

State y = "s2";         // Does NOT compile
State y("s2");          // Does compile
State y = string("s2"); // Does compile

What's going on here? Why does the first not compile, but the second and third do? As well, is my professor mistaken in saying that the first statement should work? Or is it behavior that's compiler specific?

Was it helpful?

Solution

It looks like your State object has a constructor that takes string. The literal "s2" is type const char [3]. This is why you are receiving the error.

It is also compiler specific. The following code snippet works in VS2013, yet not G++:

struct State
{
    State(string s) { }
};

int main() {
    State s = "a";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top