Jason Drain Jason Drain - 6 months ago 28
C++ Question

Cannot Compile .cpp File When Trying To Define Private Var

I am attempting to compile a .cpp file that includes a .h file and then implements the class outlined.

In String.h:

using namespace std;

class String

int _length;
char *data;
int getCharArraySize(char arr[]);

In String.cpp:

#include "String.h"

using namespace std;

* Private vars and methods
int String::_length;
char String::*data;
int String::getCharArraySize(char arr[])
//method body
return 0;

When I attempt to compile with g++ I get this error:

% g++ String.cpp -c
String.cpp:14:17: error: ‘int String::_length’ is not a static data member of ‘class String’
int String::_length;

I am only having issues with String::_length. I was initially thinking that it was due to _length being private but all the other private methods/vars, compile just fine. I also need to leave this .h file as is so I cannot just make it public. Any help would be appreciated!


Well, it's exactly as the compiler says: _length is not a static member variable. Yet, you are treating it as one by providing it with its own definition. Simply do not do that. Only static member variables should be defined like that.

The same goes for data.

By the way, if you do ever have to define a char* variable, then this is wrong:

char String::*data;

and this is right:

char* String::data;

Lexical grammar production oddities (inherited from C) notwithstanding, the * is part of the type, not the name.