rippy
rippy

Reputation: 195

Different objects in c++

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();
}

OUTPUT:

Upvotes: 0

Views: 135

Answers (3)

Rahul_cs12
Rahul_cs12

Reputation: 984

"extern" Keyword just declares object it won't define.

Why do we need the 'extern' keyword in C if file scope declarations have external linkage by default?

Upvotes: 0

user2249683
user2249683

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

rbk
rbk

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

Related Questions