Click here to Skip to main content
15,887,847 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have scenario like this.

class Books
{
protected:
   static int BookId;
   int    b;
   ;
public:
   void Init () = 0;
   SetVal (int val);
   ;
}

class Novel : public Books
{
public:
   Init (int val) {b = val}
}


I want to initialize int BookId to 0. How this can be done in efficient way without killing OOP concept ?
Posted
Updated 21-Jul-11 15:27pm
v2

Admitting you he a books.h file containing the class Books declaration,
you need a CPP file (books.cpp can be good) that does
#include "books.h"
int Books::BookId = 0;


It is basically the same as venkatmakan [^]did in his solution, but that way result in a "multiple definition" linker error, in case the "books.h" file is included by more "CPP" files.
 
Share this answer
 
Comments
Harrison H 22-Jul-11 19:53pm    
This is the only answer.
will this give error?
C#
class Books
{
protected:
   static int BookId;
   int    b;
public:
   virtual void Init () = 0; //syntax is corrected
   int SetVal (int val);
};
int Books::BookId = 0;
 
Share this answer
 
A constructor ?

Apparently I need to write more, to post my answer.
 
Share this answer
 
Comments
Member 8097131 21-Jul-11 21:35pm    
there are two problems in this solution
(1) Abstract class can not have object of it.
(2) Object of derived class will call constructor of Abstract class and initialize it to zero. So, every time object created, "a" will become zero. but i want a single time initialization thats why i kept it "static".
Sergey Chepurin 22-Jul-11 5:48am    
From MSDN (http://msdn.microsoft.com/en-us/library/c8whxhf1.aspx:)"A class that contains at least one pure virtual function is considered an abstract class. Classes derived from the abstract class must implement the pure virtual function or they, too, are abstract classes".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900