-
July 11th, 2012, 09:25 AM
#1
How to define a static member data in an abstract class?
For example, in a header file A.h, I define an abstract class,
Code:
// A.h
class A
{
public:
virtual void foo() = 0;
private:
static int _x;
};
How'd I initialize static member data _x?Normally, we initialize a static member data in a cpp file. However, there is not cpp file for A.h. If I intialize _x in header file, there will be linker errors like mulitple defined symbols. What is appropriate way to do that? Thanks.
-
July 11th, 2012, 09:48 AM
#2
Re: How to define a static member data in an abstract class?
Initialise it in a source file, e.g.,
If there is no source file, then you should create one. Do you really need a static non-const member variable, anyway?
-
July 11th, 2012, 10:15 AM
#3
Re: How to define a static member data in an abstract class?
Originally Posted by laserlight
Initialise it in a source file, e.g.,
If there is no source file, then you should create one. Do you really need a static non-const member variable, anyway?
Yes, I really need a static non-const member variable because only one copy of this variable is needed. For an abstract class to define a static member data, we always need to have a source file for an abstract class? Thanks.
-
July 11th, 2012, 10:22 AM
#4
Re: How to define a static member data in an abstract class?
Well, you need to define the static member variable somewhere. With the notable exception of static const integral member variables, this means defining it outside of the class definition. Since doing this in the header is wrong as the header may be included in multiple translation units, you should define the variable in some source file.
-
July 11th, 2012, 01:51 PM
#5
Re: How to define a static member data in an abstract class?
Originally Posted by laserlight
Well, you need to define the static member variable somewhere. With the notable exception of static const integral member variables, this means defining it outside of the class definition. Since doing this in the header is wrong as the header may be included in multiple translation units, you should define the variable in some source file.
When you said I should define the variable in some source file, you meant any source file? I tried to define the variable in A.cpp(from AA.dll), then I got linkers error from B.obj(from BB.dll). The linker errors are only caused because I define the static variable in A.cpp. Do you have any idea why it happened? Thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|