On May 1, 4:28 am, Johs <asd...@asd.comwrote:
I have this in a file called bas.h:
#ifndef BAS_H_
#define BAS_H_
class GeoObj {
public:
void draw() const;
int getNum();
private:
int num = 10;
};
#endif /*BAS_H_*/
But I get the error:
bas.h:10: error: ISO C++ forbids initialization of member 'num'
I have also tried to change "int num = 10;" to "static int num = 10";
but it still gives an error. Why does it give an error to initialize a
private field?
Because you are attempting to initialize it in a formal declaration.
What you attempting to do is the ctor's job.
// bas.h
#ifndef BAS_H_
#define BAS_H_
class GeoObj {
int num;
public:
GeoObj(); // ctor
void draw() const;
int getNum() const;
};
#endif /*BAS_H_*/
// bas.cpp
#include "bas.h"
// ctor with init list
GeoObj::GeoObj() : num(10)
{
}
void GeoObj::draw() const
{
// do stuff
}
int GeoObj::getNum() const
{
return num;
}
You can also provide an additional parametized ctor to set num.
Or use one default ctor like so...
GeoObj::GeoObj( int n = 10 ) : num( n )
{
}
Don't ignore constructors in C++, including your copy constructor.