0

Constructor

Hi. How to complete the declaration of these following class, such that the class can keep track of how many objects have been instantiated since the beginning of a program that uses it? : //answers on the wide blank spaces class Book { public: const char * getTitle() const { return m_title; } void setTitle(const char * t) { strcpy(m_title, t) } private: char m_title[256]; };

20th Sep 2018, 7:11 PM
lakas
2 Answers
+ 1
Use a static member that is to be incremented by one every time when the constructor is called. That is local to a class instead of a single instance, and will be updated whenever a new object calls the Constructor. Eg : class Book { static int book_ct; char m_title[256]; public : Book() { book_ct++; } // More code... }; int Book::book_ct=0; To check its value after some operation, you will have to use a static member, like : static void print_count() { cout<<book_ct<<" Books Exist\n"; } And then you call it in main like this : int main() { Book books[5]; Book::print_count(); // More code follows... }
21st Sep 2018, 12:58 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
0
thank you
21st Sep 2018, 3:48 AM
lakas