Thread: Display the total number of objects. Is my program correct?

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    12

    Question Display the total number of objects. Is my program correct?

    Code:
    #include<iostream>
    using namespace std;
    class Object
    {
    public:
    	static int nb_of_objects;
    	Object ()
    	{
    		 nb_of_objects++;
    	}
    	Object(const Object&){
    		cout << " Object: copy constructor " << endl;
    		nb_of_objects++;
    	}
    static void show(){ cout << "Number of objects created is:" << nb_of_objects << endl; }
    
    
    };
    int Object::nb_of_objects = 0;
    
    
    int main(){
    	Object::nb_of_objects;
    	Object o;
    	Object o2 = o;
    	o.show();
    	return 0;
    }

  2. #2
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    Looks good to me.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    nb_of_objects could be made private, since you don't access it directly (you use the show function instead). Also, remove the line

    Code:
    Object::nb_of_objects;
    in your main function. You have already provided a static member initializer for this data item, so you don't need to refer to it from main.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A simple program : To display a number I typed in
    By Nyahman in forum C Programming
    Replies: 7
    Last Post: 03-16-2016, 05:10 PM
  2. destucting objects - correct way
    By deathmetal in forum C++ Programming
    Replies: 9
    Last Post: 09-06-2015, 02:27 AM
  3. Replies: 15
    Last Post: 12-01-2012, 11:15 AM
  4. HELP with Total number of even and odd numbers (not sum)
    By jet0717 in forum C++ Programming
    Replies: 2
    Last Post: 11-09-2011, 01:51 PM
  5. C Program that counts total prime number?
    By exe101 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 01:18 AM

Tags for this Thread