开发者

C++ Destructor Exception

开发者 https://www.devze.com 2023-03-04 19:57 出处:网络
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 Wri

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 w开发者_StackOverflowriteOneLetter();
    ~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;
}


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消