Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
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 21-Jul-11 14:39pm
Edited 21-Jul-11 15:27pm
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  
Comments
Harrison H at 22-Jul-11 19:53pm
   
This is the only answer.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

A constructor ?
 
Apparently I need to write more, to post my answer.
  Permalink  
Comments
Member 8097131 at 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 at 22-Jul-11 5:48am
   
From MSDN (http://msdn.microsoft.com/en-us/library/c8whxhf1.aspx:)"A class that contains at least one pure <i>virtual</i> function is considered an abstract class. Classes derived from the abstract class must implement the pure virtual function or they, too, are abstract classes".
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

will this give error?
class Books
{
protected:
   static int BookId;
   int    b;
public:
   virtual void Init () = 0; //syntax is corrected
   int SetVal (int val);
};
int Books::BookId = 0;
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 534
1 OriginalGriff 312
2 Damith Weerasinghe 300
3 thatraja 220
4 ravikhoda 210
0 Sergey Alexandrovich Kryukov 10,974
1 OriginalGriff 6,667
2 Peter Leow 4,760
3 Abhinav S 3,813
4 Maciej Los 3,565


Advertise | Privacy | Mobile
Web01 | 2.8.140421.2 | Last Updated 22 Jul 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid