Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ compiling error related to constructor/destructor definition

People also ask

What is constructor and destructor in C?

Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object.

How is a destructor defined?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .

Can a destructor be called directly?

No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.

What is destructor C++?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.


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()'