1

Followed codes runs properly with Eclipse but when i run on Dev C++ IDE i am getting followed error;

City.cpp:6: error: expected primary-expression before '{' token

City.h

#include <string>

using namespace std;

#ifndef CITY_H
#define CITY_H

class City
{
    public:
        City();
        string arrCity[10];
};

#endif // CITY_H

City.cpp

#include <string>
#include "City.h"

City::City()
{
    arrCity[10] = {"Tbilisi", "Batumi", "Kutaisi", "Gori", "Poti"};        
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Goran Zooferic
  • 371
  • 8
  • 23

1 Answers1

3

arrCity[10] = {"Tbilisi", "Batumi", "Kutaisi", "Gori", "Poti"}; doesn't do what you expected. It's trying to assign arrCity[10] (i.e. a std::string) by a braced initializer list; that won't work. And it's getting out of the bound of the array.

Note that array can't be assigned directly, you can use member intializer list to initialize it like:

City::City() : arrCity {"Tbilisi", "Batumi", "Kutaisi", "Gori", "Poti"}
{
}

or use default member initializer:

class City
{
    public:
        City();
        string arrCity[10] = {"Tbilisi", "Batumi", "Kutaisi", "Gori", "Poti"};
        // or
        string arrCity[10] {"Tbilisi", "Batumi", "Kutaisi", "Gori", "Poti"};
};

Note that both the above solutions needs C++11 supports, otherwise, you might need to assign every element one by one in the constructor's body.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Firstly, thank you for your help, unfortunately it doesn't work. also it returned new error City.cpp: In constructor `City::City()': City.cpp:4: error: expected `(' before '{' token City.cpp:4: confused by earlier errors, bailing out – Goran Zooferic Apr 27 '17 at 08:15
  • @GoranZooferic [DEMO](http://rextester.com/VANOK33865) Does your compiler support C++11? – songyuanyao Apr 27 '17 at 08:32