1
class CBAY_ITEM
{
public:

    string name = enterName();
    string condition = enterCondition();

};

when I compile, it gives 4 errors, which say

1.a function call cannot appear in a constant-expression

2.ISO C++ forbids initialization of member 'name'

3.making 'name' static

4.invalid in-class initialization of static data member of non-integral type 'std::string'

what am I doing wrong here??

2
  • It would really help if you told us what you were trying to do. It's not clear from the code what those are supposed to be or when you expected that code to run. Commented Apr 28, 2013 at 1:15
  • @DavidSchwartz I am trying to create a dynamic linked list using the class definition I provided.
    – user2086751
    Commented Apr 28, 2013 at 1:21

2 Answers 2

5

You cannot initialize members at their declaration in C++03, unless they are static const members being initialized with constant expressions. Constant expressions cannot contain function calls in C++03.

Either switch to C++11 (-std=c++11 or -std=c++0x with gcc or clang) or initialize the members in the CBAY_ITEM's constructor. If you have several constructors that perform a common initialization, you can move the common initialization to a helper init method.

class CBAY_ITEM {
  std::string name;
  std::string condition;
public:
  CBAY_ITEM() : name(enterName()), condition(enterCondition())
    {}
};
2
  • @syam If he uses C++11 he will never end up in that situation in the first place ;)
    – pmr
    Commented Apr 28, 2013 at 0:54
  • I guess I will just use a simple struct just to be sure it runs on my teachers computer because I dont know if he has c++03 or c++11
    – user2086751
    Commented Apr 28, 2013 at 0:57
-1

Do you want to initialize those values in your class? Use a constructor.

#include <string>
std::string enterName();
std::string enterCondition();
class CBAY_ITEM
{
public:
  std::string name;
  std::string condition;
  CBAY_ITEM() {
    name = enterName();
    condition = enterCondition();
  }
};
4
  • 4
    What about initializer lists? -1
    – syam
    Commented Apr 28, 2013 at 0:43
  • I use initializer lists a lot myself. But it's not something you teach to someone who is just learning the syntax for classes.
    – Hal Canary
    Commented Apr 28, 2013 at 2:31
  • 1
    I beg to differ. Teaching bad practices (and on purpose, at that) is not helpful in any way IMHO. But I guess you won't be convinced otherwise, and I certainly won't either so let's keep it at that. ;)
    – syam
    Commented Apr 28, 2013 at 9:29
  • When I was first learning C++, I was confused by a lot of the syntax.
    – Hal Canary
    Commented Apr 29, 2013 at 2:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.