C++ question: what is "class UserDefinedType* MemberName;" when declared as a property of a class?

Viewed 88

I would expect the declaration of a user-defined type member variable (a pointer to be specific) to look something like:

...
public:
  UserDefinedType* MemberName;
...

But I've seen this in a few examples:

...
public:
  class UserDefinedType* MemberName;
...

Apologies for what I'm sure is an obvious question to answer, I just don't really know what to search for. I've looked at nested classes in C++, but I'm unsure if that's what is happening here. Honestly feels like a somewhat redundant identifier.

Any comments, links, corrections, are appreciated thank you.

1 Answers

That's a forward declaration

class UserDefinedType {
}; 
 
class A { 
  public:
     UserDefinedType * member1; // this is ::UserDefinedType
     class UserToBeDefinedType; // forward declaration
     UserToBeDefinedType * member2; // this is A::UserDefinedType
}; 
 
class A::UserToBeDefinedType { // define the class 
};
 
int main()
{
    A a;
    a.member1 = new UserDefinedType;    // OK
    //a.member2 = new UserDefinedType;  // KO
    //a.member1 = new A::UserDefinedType; // KO
    a.member2 = new A::UserToBeDefinedType; // OK
}

Run and test the code

Maybe read this

EDIT: Enhance the quality of example and add link to run code

Related