jeudi 5 juillet 2018

Invoking constructor without an object

I forgot to add the object name in front of class name , but the code still compiled and constructor got invoked . I am really bamboozled what actually happened here. Does not it mean that we can invoke the constructor without creating an object?

My code :

#include<iostream>
using namespace std;

class PrintJobs
{
    private:
        int nPages;
        static int nTrayPages;
        static int nJobs;

    public:
        PrintJobs(int np) : nPages(np)
        {
            nJobs++;
            cout << "Printing " <<  nPages <<"pages" << endl;
        }
        ~PrintJobs()
        {
            --nJobs;
        }

        static int getJobs()
        {
            return nJobs;
        }

        static int checkPages()
        {
            return nTrayPages;
        }

        static void loadPages(int n)
        {
            nTrayPages += n ;
        }

};

int PrintJobs::nTrayPages = 500 ;
int PrintJobs::nJobs = 0 ;

int main()
{
    cout << "Jobs  " << PrintJobs::getJobs() << "\n" ;
    cout << "Pages " << PrintJobs::checkPages() << "\n";

    PrintJobs(10); /// This is the line I am confused about.

    cout << "Jobs  " << PrintJobs::getJobs() << "\n" ;
    cout << "Pages " << PrintJobs::checkPages() << "\n";
    {
        PrintJobs p(30) , p2(20);
        cout << "Jobs  " << PrintJobs::getJobs() << "\n" ;
            cout << "Pages " << PrintJobs::checkPages() << "\n";
            PrintJobs::loadPages(100);

    }

    cout << "Jobs  " << PrintJobs::getJobs() << "\n" ;
    cout << "Pages " << PrintJobs::checkPages() << "\n";
}

OutPut :

enter image description here

Aucun commentaire:

Enregistrer un commentaire