2

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.

nfgrep
  • 35
  • 1
  • 3
  • 4
    You could use that to avoid a separate forward declaration of the type `UserDefinedType`. Perhaps `UserDefinedType` is not known to the compiler at this point in the file. – drescherjm Jul 21 '21 at 15:29
  • 2
    Related to forward declarations: [https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c](https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c) – drescherjm Jul 21 '21 at 15:40

1 Answers1

3

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

Oussama Ben Ghorbel
  • 2,132
  • 4
  • 17
  • 34