Al T
Al T

Reputation: 41

C++ Destructor Exception

I am a novice programmer working on some code for school. When the following code is executed, the word BAD is output. I do not understand why the letter C in the destructor is not output when the WriteLettersObj object is terminated.

// Lab 1 
//
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class WriteLetters {
public:
    WriteLetters();
    void writeOneLetter();
    ~WriteLetters();
} WriteLettersObj;

WriteLetters::WriteLetters() {
    cout << "B";
}

void WriteLetters::writeOneLetter() {
    cout << "A";
}

WriteLetters::~WriteLetters() {
    cout << "C" << endl;
}

int main() {
    WriteLettersObj.writeOneLetter();
    cout << "D";
    getch();

    return 0;
}

Upvotes: 1

Views: 319

Answers (3)

Thomas L Holaday
Thomas L Holaday

Reputation: 13862

You are mixing iostream with non-ANSI conio.h.

Make this change:

// getch();
cin.get();

Hey presto, the C appears. At least on OS X it does. And Ubuntu.

Upvotes: 2

Aater Suleman
Aater Suleman

Reputation: 2328

I tried running your code without getch on linux and Mac and it runs just fine. @iammilind is right that you should move getch in the destructor.

Upvotes: 0

iammilind
iammilind

Reputation: 70094

Your program is live until you exit the main() with return 0 instruction. Since the WriteLettersObj is a global variable, it will be constructed before main() starts and destructed after main() finishes and not after getch().

To see your output getting printed, put getch() in the end of destructor.

Upvotes: 1

Related Questions