[comp.lang.c++] How to reference a member?

menqjuh@grad1.cis.upenn.edu (06/05/90)

When I compile the following segment of code by g++(1.36), I get the error 
message "structure has no member named `name'." 

============================================================
#include <stream.h>

class String {
    int length;
    char *head;
  public:
    String(int len) { head = new char[length = len + 1]; }
};

struct Person {
    String name(25);
    int age;
};

main()
{
    Person pp;
    pp.name;    // This reference is *not* allowed. WHY?
}
============================================================

Is this behavior normal or abnormal?  

In my case, `name' is desired to be of `String' type instead of `String*'
type, and the length of the `name' (25 above) is subject to change.

Any help will be appreciated.

Menq-Juh Lee

pkturner@cup.portal.com (Prescott K Turner) (06/07/90)

Menq-Juh Lee writes:
> struct Person {
>     String name(25);
>     int age;
> };

You can't give the argument to String's constructor in the declaration
of Person.  A C++ compiler should reject the above declaration of the 
'name' member.  Try:

struct Person {
    String name;
    int age;
    Person();  // default constructor for Person
};
Person::Person : name(25) {}  // constructor definition initializes 'name'
--
Prescott K. Turner, Jr.
Language Processors, Inc.
959 Concord St., Framingham, MA 01701 USA    (508) 626-0006 x232
UUCP: ...sun!cup.portal.com!pkturner    Internet: pkturner@cup.portal.com