How to allocate a static class attribute in c++?

H

herman

Hi,

I have a static class attribute in my class:

class A
{
public:
static B aB;
}

How can I allocate this static class attribute?

I think I need to do this

A::aB = ??? ;

If I do this:

A::aB = new B(); // where/when will aB be deleted if I allocate it on
the heap?

If I dont do anything, I have this linker error:

A.cpp:229: undefined reference to `A::aB'
 
V

Victor Bazarov

herman said:
I have a static class attribute in my class:

class A
{
public:
static B aB;
}
;

And it's not really "an attribute", it's *a data member*.
How can I allocate this static class attribute?

I think I need to do this

A::aB = ??? ;

Close. You need to do

B A::aB;

if your 'B' class has a default constructor, or

B A::aB( ??? );

(replace ??? with proper constructor arguments) if your 'B' class
requires arguments for its construction.
If I do this:

A::aB = new B(); // where/when will aB be deleted if I allocate it on
the heap?

Don't. You need to un-learn your Java habits of using 'new' for
everything.
If I dont do anything, I have this linker error:

A.cpp:229: undefined reference to `A::aB'

Correct. You do need to define any static member (except if it has
a constant integral type and the address of it is never taken).

V
 
N

Neelesh Bodas

Hi,

I have a static class attribute in my class:

class A
{
public:
static B aB;

}

How can I allocate this static class attribute?

aB is a data member, not a pointer. You shouldnot call "new" for
allocating (as you did below)
Simply saying

B A::aB;

will work, provided the definition of B is in scope, and constructor
B::B() is callable.
I think I need to do this

A::aB = ??? ;

If I do this:

A::aB = new B(); // where/when will aB be deleted if I allocate it on
the heap?

you can't do this, since aB is not a pointer
If I dont do anything, I have this linker error:

A.cpp:229: undefined reference to `A::aB'

Finally, lookup "static initialization order fiesco" :
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12

-N
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,051
Members
47,656
Latest member
rickwatson

Latest Threads

Top