Reputation: 195
This program displays different types of object in c++ using constructor. I have attached a snapshot of the output. In the output, why isn't there a message displayed for the creation of the extern object?
//Program to illustrate different type of objects
#include<iostream.h>
#include<conio.h>
#include<string.h>
class diffobjs{
public:
char msg[10];
diffobjs(char ar[]){
strcpy(msg,ar);
cout<<"\nObject created of type "<<msg;
}
~diffobjs(){
cout<<"\n"<<msg<<" object destroyed";
getch();
}
};
extern diffobjs d1("Global");
void main(){
clrscr();
diffobjs d2("Automatic");
static diffobjs d3("Static");
getch();
}
Upvotes: 0
Views: 135
Reputation:
Fixing some issues:
//Program to illustrate different type of objects
// Standard C++ headers have no .h
#include<iostream>
// Not portable
// #include<conio.h>
// This <string.h> and other C headers are replaced by c... headers
// #include<cstring>
class diffobjs{
public:
// Have a std std::string to avoid buffer overflows
std::string msg;
diffobjs(const std::string& s)
// Use initialization
: msg(s)
{
std::cout<<"Object created of type "<<msg<<'\n';
}
~diffobjs() {
std::cout<<msg<<" object destroyed"<<'\n';
}
};
// A declaration would go in a header
extern diffobjs d1;
// The definition is without 'extern'
diffobjs d1("Global");
int main(){
// Globals are initialized before main
// Remove the non-portable clrscr();
// clrscr();
std::cout << "\n[Entering Main]\n\n";
diffobjs d2("Automatic [1]");
// A static in a function is initialized only once, the static has an impact on
// the order of destruction.
static diffobjs d3("Static");
// Added
diffobjs d4("Automatic [2]");
// You might not see destruction, if you start the programm in your IDE
// Hence, remove the non-portable getch()
// getch();
std::cout << "\n[Leaving Main]\n\n";
}
Upvotes: 2
Reputation: 11
The line with the extern keyword does not define the object, but only forward declares it. If you remove this keyword and leave the rest of the line, a global object will be created.
Upvotes: 1