Question

Made this simple class with MSVC++ 6.0

class Strg
{
public:
    Strg(int max);
private:
    int _max;
};


Strg::Strg(int max)
{
  _max=max;
}

Sounds good if I use it in :

main()
{
  Strg mvar(10);
}

But Now If I use it in an another class :

class ok
{
public:
    Strg v(45);
};

I get message error : error C2059: syntax error : 'constant'

Could you tell me more please ?

No correct solution

OTHER TIPS

Should be:

class ok
{
public:
    Strg v;
    ok() : v(45) {}
};

Non-static member variables that don't have default constructors (v in this case) should be initialized using initialization lists. In functions (like main) on the other hand you can use the regular constructor syntax.

What the compiler is complaining about is that you are trying to provide instruction on how ton instantiate the class member v inside your class definition, which is not allowed.

The place to instantiate v would be inside the contructor, or in the constructor's initializer list. For example:

Inside constructor:

class ok
{
public:
    Strg v;
    ok() {
        v = Strg(45);
    }
};

In initializer list:

class ok
{
public:
    Strg v;
    ok() : v(45) {}
};

The correct way to do it is the last one (otherwise, v would also require a default constructor and would be initialized twice).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top