[comp.lang.c++] Static members of class type

dfoster@jarthur.Claremont.EDU (Derek R. Foster) (02/22/91)

How do I tell a C++ compiler to call the constructor of a static
member variable of class type?

In other words, how does one initialize
a member of a class that is itself a class?

In still other words and symbols:

class A
{
  A(int x) {do something};
};

class B
{
  B(int y) {do something else};
  static int membervariable;
  static A memberclass;
}

B somevariable;

When I attempt to compile this in Turbo C++, I found (after about three
days of tracking this down) that the constructor for A never gets called,
evidentally because the only instance of A is as a member function. Is
it supposed to happen this way? In fact, TC++ won't even let me do something
like:

class B
{
  ...
  B(int x) : memberclass(x) {do something else};  // this doesn't work!
  ...
}

It says that I can't construct memberclass here. I thought about trying
to initialize A outside its class definition, like what is usually done for
static member variables, like:

A B::membervariable = 5;

i.e. making an additional declaration that would call the constructor, like:

A B::memberclass(42);

but TC++ says that I'm trying to declare memberclass() outside of its class
declaration (which is perfectly true! Why won't it let me?)

I'm out of ideas. Has anyone run into this problem before? What is the proper
syntax? How do I tell a C++ compiler to call the constructor of a static
member variable of class type? Is this a bug in TC++?

If you reply to this, please send me Email as well, since I don't often
read this newsgroup, and our site only holds it for a few days.

Thanks for any help!

Derek Riippa Foster

rfg@NCD.COM (Ron Guilmette) (03/03/91)

In article <10927@jarthur.Claremont.EDU> dfoster@jarthur.Claremont.EDU (Derek R. Foster) writes:
+How do I tell a C++ compiler to call the constructor of a static
+member variable of class type?
+
+class A
+{
+  A(int x) {do something};
+};
+
+class B
+{
+  B(int y) {do something else};
+  static int membervariable;
+  static A memberclass;
+}
+
+A B::memberclass(42);
+
+but TC++ says that I'm trying to declare memberclass() outside of its class
+declaration (which is perfectly true! Why won't it let me?)
+
+... How do I tell a C++ compiler to call the constructor of a static
+member variable of class type? Is this a bug in TC++?

In a word, yes.  The declaration:

	A B::memberclass(42);

should be allowed.

-- 

// Ron Guilmette  -  C++ Entomologist
// Internet: rfg@ncd.com      uucp: ...uunet!lupine!rfg
// New motto:  If it ain't broke, try using a bigger hammer.