c++ compiling error related to constructor/destructor definition

caesar picture caesar · Apr 2, 2009 · Viewed 32.9k times · Source

I'm trying to define the constructor and destructor of my class but I keep getting the error:

definition of implicitly-declared 'x::x()'

What does it mean?

Part of the code:

///Constructor
StackInt::StackInt(){
    t = (-1);
    stackArray = new int[20];
};

///Destructor
StackInt::~StackInt(){
    delete[] stackArray;
}

Answer

Michael Burr picture Michael Burr · Apr 2, 2009

In the class declaration (probably in a header file) you need to have something that looks like:

class StackInt {
public:
    StackInt();
    ~StackInt();  
}

To let the compiler know you don't want the default compiler-generated versions (since you're providing them).

There will probably be more to the declaration than that, but you'll need at least those - and this will get you started.

You can see this by using the very simple:

class X {
        public: X();   // <- remove this.
};
X::X() {};
int main (void) { X x ; return 0; }

Compile that and it works. Then remove the line with the comment marker and compile again. You'll see your problems appear then:

class X {};
X::X() {};
int main (void) { X x ; return 0; }

qq.cpp:2: error: definition of implicitly-declared `X::X()'